From 435305e42a2043b99a648691ebb3741ca02309f3 Mon Sep 17 00:00:00 2001 From: Reactorcoremeltdown Date: Mon, 16 Nov 2026 10:01:14 +0100 Subject: [PATCH] iOS 0.5.0: hand-built editors (Tape Delay, Tape Engine, Mix Tightener, Granular scope, Wavetable tables, Grain Cloud source) Effect visualisation through the C++ effect, engine and AU; custom wavetables and grain sources load and persist with the song; the app's slot editor hosts the file picker for bespoke views. Co-Authored-By: Claude Opus 5.5 --- ios/CHANGELOG.md | 17 ++ ios/Makefile | 2 +- ios/PORTING.md | 2 +- ios/app/FX/Bridging.h | 1 + ios/app/FX/Editor/AUDataSource.swift | 4 + ios/app/FX/Editor/Bespoke/Bespoke.swift | 14 + ios/app/FX/Editor/Bespoke/DelayBespoke.swift | 95 +++++- .../FX/Editor/Bespoke/GrainCloudBespoke.swift | 139 ++++++++- .../FX/Editor/Bespoke/GranularBespoke.swift | 132 ++++++++- .../Editor/Bespoke/MixTightenerBespoke.swift | 92 +++++- .../FX/Editor/Bespoke/TapeEngineBespoke.swift | 187 +++++++++++- .../FX/Editor/Bespoke/WavetableBespoke.swift | 158 +++++++++- ios/app/FX/Editor/DeviceModel.swift | 3 + ios/app/FX/SizzleDeviceAU+Sources.h | 30 ++ ios/app/FX/SizzleDeviceAU+Sources.mm | 66 +++++ ios/app/FX/SizzleEffectAU.h | 8 + ios/app/FX/SizzleEffectAU.mm | 32 ++- .../Host/Bespoke/SlotDataSource+Sources.swift | 44 +++ ios/app/Host/Bespoke/SlotDataSource+Viz.swift | 18 ++ ios/app/Host/Bridging.h | 1 + ios/app/Host/Screens/Toolbox/SlotEditor.swift | 16 +- ios/app/Host/SizzleSession+Sources.h | 32 ++- ios/app/Host/SizzleSession+Sources.mm | 272 ++++++++++++++++++ ios/app/Host/SizzleSession+Viz.h | 9 + ios/app/Host/SizzleSession+Viz.mm | 27 ++ ios/app/project.yml | 1 + ios/app/tests/ScreenBridging.h | 1 + ios/app/tests/SnapshotBridging.h | 1 + ios/app/tests/au_test.mm | 37 ++- ios/core/include/sizzle/Effect.hpp | 13 + ios/core/include/sizzle/Engine.hpp | 6 +- ios/core/src/engine/Engine.cpp | 42 ++- ios/core/src/fx/GranularGlitch.cpp | 46 ++- versions.properties | 4 +- 34 files changed, 1514 insertions(+), 38 deletions(-) create mode 100644 ios/app/FX/SizzleDeviceAU+Sources.h create mode 100644 ios/app/FX/SizzleDeviceAU+Sources.mm create mode 100644 ios/app/Host/Bespoke/SlotDataSource+Sources.swift create mode 100644 ios/app/Host/Bespoke/SlotDataSource+Viz.swift diff --git a/ios/CHANGELOG.md b/ios/CHANGELOG.md index 6135689..86659d3 100644 --- a/ios/CHANGELOG.md +++ b/ios/CHANGELOG.md @@ -3,6 +3,23 @@ Sizzle for iOS/iPadOS (`cc.tiredsysadmin.ios.sizzle`). One entry per version in `../versions.properties` (`ios.versionName` / `ios.versionCode`). +## 0.5.0 (build 10) + +- The hand-built editors of the Android app, in the app and in the plugins: + - Tape Delay: four tape heads, each an on/off toggle over a vertical fader + that snaps to the delay divisions, then Feedback / Mix / Tape. + - Tape Engine: the reel-to-reel transport, reels turning with the tape speed; + hold a reel to brake the tape (pitch dives, then springs back). + - Mix Tightener: Strength plus the EQ / Comp / Limit stage trims. + - Granular Glitch: the live oscilloscope with the jumping read head (once the + effect sits on a channel with signal), and the Intensity slider. + - Wavetable: each oscillator's table drawn, the playing frame lit; LOAD TABLE + turns your own WAV (Serum, WaveEdit, power-of-two frames) into the Custom table. + - Grain Cloud: the source waveform with START..END lit; LOAD WAV takes your own + WAV, SF2 or XI as the source. +- Loading your own tables and sources works in the app; inside AUM the plugins + can't reach your files yet. + ## 0.4.1 (build 9) - Fix: clearing a Toolbox tile, deleting a preset, and importing a WAV, SF2/XI diff --git a/ios/Makefile b/ios/Makefile index 5d2461a..506b13d 100644 --- a/ios/Makefile +++ b/ios/Makefile @@ -86,7 +86,7 @@ core-test: build/core/golden_test build/core/sampler_test build/core/engine_test build/core/io_test $(GOLDEN)/songs ../app/src/test/resources/mikroseq # ------------------------------------------------------------------ app -AU_SRC := app/FX/SizzleDeviceAU.mm app/FX/SizzleEffectAU.mm app/FX/SizzleInstrumentAU.mm +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) \ diff --git a/ios/PORTING.md b/ios/PORTING.md index a680e82..19d90c6 100644 --- a/ios/PORTING.md +++ b/ios/PORTING.md @@ -91,7 +91,7 @@ AUv3s is the per-plugin process round trip, which the in-app host avoids. (demo and midifx bit for bit; mix and waltz within 1e-5, from the Tape Engine's known one-ulp difference fed through the rest of the song). Not ported: audio output (the app calls `fillBlock`), WAV writing (`MasterSink`), CoreMIDI (the - engine fills the outgoing queue, `pollMidiOut`), effect scope/playhead views. + engine fills the outgoing queue, `pollMidiOut`), effect scope/playhead views (done in 0.5.0: Granular Glitch). Decisions: the voice pools are built in AudioEngine's field order from `EngineGlobals` (clock and seed counters); swapped FX chains and playlists are freed by a later main-thread rebuild once the audio thread has finished a block; diff --git a/ios/app/FX/Bridging.h b/ios/app/FX/Bridging.h index 5014fa4..ad72022 100644 --- a/ios/app/FX/Bridging.h +++ b/ios/app/FX/Bridging.h @@ -1 +1,2 @@ #import "SizzleDeviceAU.h" +#import "SizzleDeviceAU+Sources.h" diff --git a/ios/app/FX/Editor/AUDataSource.swift b/ios/app/FX/Editor/AUDataSource.swift index 4e8c80a..410081f 100644 --- a/ios/app/FX/Editor/AUDataSource.swift +++ b/ios/app/FX/Editor/AUDataSource.swift @@ -9,4 +9,8 @@ import Foundation final class AUDataSource: DeviceDataSource { let au: SizzleDeviceAU init(au: SizzleDeviceAU) { self.au = au } + + // Hidden settings live in the AU's state (saved with host sessions). + func hiddenValue(_ key: String) -> String? { au.hiddenValue(forKey: key) } + func setHiddenValue(_ value: String, key: String) { au.setHiddenValue(value, forKey: key) } } diff --git a/ios/app/FX/Editor/Bespoke/Bespoke.swift b/ios/app/FX/Editor/Bespoke/Bespoke.swift index e0944f6..3893792 100644 --- a/ios/app/FX/Editor/Bespoke/Bespoke.swift +++ b/ios/app/FX/Editor/Bespoke/Bespoke.swift @@ -36,6 +36,20 @@ extension DeviceDataSource { func setHiddenValue(_ value: String, key: String) {} } +/// A host's file picker for bespoke views (the app's slot editor provides one: on +/// iOS 15 a .fileImporter nested inside another one may not present). A view +/// calls it with what to do with the picked URL; without one (the plugins) it +/// uses its own .fileImporter. +private struct DeviceFilePickerKey: EnvironmentKey { + static let defaultValue: ((@escaping (URL) -> Void) -> Void)? = nil +} +extension EnvironmentValues { + var deviceFilePicker: ((@escaping (URL) -> Void) -> Void)? { + get { self[DeviceFilePickerKey.self] } + set { self[DeviceFilePickerKey.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 17d3655..312730d 100644 --- a/ios/app/FX/Editor/Bespoke/DelayBespoke.swift +++ b/ios/app/FX/Editor/Bespoke/DelayBespoke.swift @@ -3,8 +3,99 @@ import SwiftUI -/// The Delay's hand-built editor parts (stub: card layout until ported). +/// The Tape Delay's hand-built editor (Android's DelayEditor): four tape heads side +/// by side, each an on/off toggle above a vertical division fader that snaps hard to +/// the DelayDivisions steps (1/1 at the top … 1/16T at the bottom; a longer division +/// fills taller), then the Loop card (Feedback / Mix / Tape). Feedback's maximum is +/// the DSP's ceiling (0.9), so the loop can't run away. @MainActor enum DelayBespoke { - static func body(_ model: DeviceModel) -> AnyView? { nil } + static func body(_ model: DeviceModel) -> AnyView? { AnyView(DelayEditorView(model: model)) } + + static let heads = 4 + /// Android's DelayDivisions labels, longest first (used when DeviceLayouts.json is missing). + static let fallbackDivisions = ["1/1", "1/2.", "1/2", "1/4.", "1/2T", "1/4", "1/8.", + "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) +} + +private struct DelayEditorView: View { + @ObservedObject var model: DeviceModel + + var body: some View { + VStack(alignment: .leading, spacing: 10) { + Text("Tape heads — drag a fader to set its time; tap the number to switch it off/on:") + .font(Theme.mono(11)).foregroundColor(Theme.dim) + .fixedSize(horizontal: false, vertical: true) + HStack(alignment: .top, spacing: 8) { + ForEach(0..= 0.5 + let idx = Swift.min(steps - 1, Swift.max(0, Int(model.value(divKey)))) + let border = on ? Theme.accent : Theme.grid + + VStack(spacing: 4) { + Text("\(head + 1)").font(Theme.mono(13)) + .foregroundColor(on ? Theme.accent : Theme.dim) + .frame(maxWidth: .infinity, minHeight: 26, maxHeight: 26) + .background(on ? Theme.accent.opacity(0.22) : Theme.surface) + .overlay(Rectangle().stroke(border, lineWidth: 1)) + .contentShape(Rectangle()) + .onTapGesture { model.set(onKey, on ? 0 : 1) } + + GeometryReader { g in + Canvas { ctx, size in + let stepH = size.height / CGFloat(steps) + let top = CGFloat(idx) * stepH + // Fill from the bottom up to the selected step: longer = taller. + ctx.fill(Path(CGRect(x: 0, y: top, width: size.width, height: size.height - top)), + with: .color((on ? Theme.accent : Theme.grid).opacity(0.45))) + var lines = Path() + for s in 1.. Double? +} + +/// 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.) @MainActor enum GrainCloudBespoke { - static func header(_ model: DeviceModel) -> AnyView? { nil } + static func header(_ model: DeviceModel) -> AnyView? { AnyView(GrainSourceStrip(model: model)) } + + static let buckets = 300 + + /// Peaks by source (a built-in source's name, or a custom sample id): each + /// sample's peaks are computed once, not per drawing. + private static var cache: [String: (peaks: [Float], seconds: Double?)] = [:] + + static func source(key: String, data: DeviceDataSource?) -> (peaks: [Float], seconds: Double?)? { + if let c = cache[key] { return c } + guard let p = data?.samplePeaks(key: "source", buckets: buckets), !p.isEmpty else { return nil } + let c = (peaks: p, seconds: (data as? SampleLengthSource)?.sampleSeconds(key: "source")) + if cache.count > 32 { cache.removeAll() } + cache[key] = c + return c + } +} + +struct GrainSourceStrip: View { + @ObservedObject var model: DeviceModel + @State private var pickerShown = false + @Environment(\.deviceFilePicker) private var hostPicker + @State private var importError: String? + /// Bumped while a built-in source is still being rendered, to look again. + @State private var retry = 0 + + var body: some View { + let name = model.choice("source") + let custom = name == "Custom" + let id = custom ? model.data?.hiddenValue("sfSample") : nil + let unloaded = custom && id == nil + let src = unloaded ? nil : GrainCloudBespoke.source(key: custom ? "C|" + (id ?? "") : "F|" + name, data: model.data) + let caption: String = { + if unloaded { return "Source: your own — load a sound." } + guard let s = src else { return "Source: \(name) (preparing…)" } + let label = custom ? "your own" : name + return s.seconds.map { String(format: "Source: %@ · %.1f s", label, $0) } ?? "Source: \(label)" + }() + VStack(alignment: .leading, spacing: 8) { + HStack(spacing: 8) { + Text("LOAD WAV").font(Theme.mono(12)).foregroundColor(Theme.accent) + .padding(.horizontal, 10).padding(.vertical, 6) + .background(Theme.surface) + .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 } } + Spacer(minLength: 0) + } + Text(caption).font(Theme.mono(10)).foregroundColor(Theme.dim) + if let s = src { + let start = CGFloat(model.value("start")), end = CGFloat(model.value("end")) + Canvas { ctx, size in draw(s.peaks, start: start, end: end, in: ctx, size: size) } + .frame(maxWidth: .infinity, minHeight: 64, maxHeight: 64) + .background(Theme.surface) + } + } + // The completion needs nothing but the picked URL (iOS 15 resets the + // presentation binding before calling it). + .fileImporter(isPresented: $pickerShown, allowedContentTypes: [.item], allowsMultipleSelection: false) { result in + guard case .success(let urls) = result, let url = urls.first else { return } + load(url) + } + .alert("Import failed", isPresented: Binding(get: { importError != nil }, set: { if !$0 { importError = nil } }), + actions: { Button("OK") { importError = nil } }, message: { Text(importError ?? "") }) + .task(id: retry) { + guard src == nil, !unloaded, retry < 60 else { return } + try? await Task.sleep(nanoseconds: 300_000_000) + retry += 1 + } + } + + private func draw(_ peaks: [Float], start: CGFloat, end: CGFloat, in ctx: GraphicsContext, size: CGSize) { + let a = Swift.min(start, end) * size.width, b = Swift.max(start, end) * size.width + ctx.fill(Path(CGRect(x: a, y: 0, width: b - a, height: size.height)), with: .color(Theme.accent.opacity(0.18))) + let bw = size.width / CGFloat(peaks.count), mid = size.height / 2 + var path = Path() + for (i, p) in peaks.enumerated() { + let x = (CGFloat(i) + 0.5) * bw, h = Swift.max(0.5, CGFloat(p) * mid) + path.move(to: CGPoint(x: x, y: mid - h)) + path.addLine(to: CGPoint(x: x, y: mid + h)) + } + ctx.stroke(path, with: .color(Theme.text), lineWidth: 1) + } + + private func load(_ url: URL) { + guard let data = model.data else { importError = "Not available here yet."; return } + if let err = data.loadFile(url, kind: "grainSource") { importError = err; return } + // The cloud now plays its own source; show that (the backend wrote the same). + if let i = model.params["source"]?.choices.firstIndex(of: "Custom") { model.set("source", Float(i)) } + } +} + +// MARK: - plug-in backend + +extension AUDataSource: SampleLengthSource { + /// The built-in source the `source` setting names (no sample store for your own yet). + private func builtInSource(_ key: String) -> String? { + guard key == "source", au.toolboxType == "GRAIN_CLOUD", + let p = au.parameterTree?.allParameters.first(where: { $0.identifier == "source" }), + let names = p.valueStrings, !names.isEmpty else { return nil } + let name = names[Swift.max(0, Swift.min(names.count - 1, Int(p.value.rounded())))] + return name == "Custom" ? nil : name + } + + func samplePeaks(key: String, buckets: Int) -> [Float]? { + guard let name = builtInSource(key), + let d = SizzleDeviceAU.grainSourcePeaks(named: name, buckets: buckets, blocking: Snapshot.active) else { return nil } + return WavetableBespoke.floats(d) + } + + func sampleSeconds(key: String) -> Double? { + guard let name = builtInSource(key) else { return nil } + let s = SizzleDeviceAU.grainSourceSeconds(named: name) + return s > 0 ? s : nil + } + + /// Wavetables and Grain Cloud sources come from the app's sample store, which + /// the plug-in doesn't share yet. + func loadFile(_ url: URL, kind: String) -> String? { + switch kind { + case "wavetable": return "Load your own wavetables in the Sizzle app for now; the plug-in plays the built-in tables." + case "grainSource": return "Load your own sounds in the Sizzle app for now; the plug-in plays the built-in sources." + default: return "Not available here yet." + } + } } diff --git a/ios/app/FX/Editor/Bespoke/GranularBespoke.swift b/ios/app/FX/Editor/Bespoke/GranularBespoke.swift index bd15d6e..90ad75d 100644 --- a/ios/app/FX/Editor/Bespoke/GranularBespoke.swift +++ b/ios/app/FX/Editor/Bespoke/GranularBespoke.swift @@ -3,8 +3,136 @@ import SwiftUI -/// The Granular's hand-built editor parts (stub: card layout until ported). +/// The Granular Glitch's editor (Android's GranularEditor): a dotted oscilloscope of +/// the sound passing through with the granular read head drawn as a jumping +/// playhead, and one horizontal Intensity slider below. The scope only shows data +/// while the effect is running on signal (a mixer channel's FX in the app; render +/// resources allocated in the plugin). @MainActor enum GranularBespoke { - static func body(_ model: DeviceModel) -> AnyView? { nil } + static func body(_ model: DeviceModel) -> AnyView? { AnyView(GranularEditorView(model: model)) } +} + +private struct GranularEditorView: View { + @ObservedObject var model: DeviceModel + + var body: some View { + let intensity = Swift.min(Swift.max(model.value("intensity"), 0), 1) + VStack(spacing: 8) { + GranularScope(data: model.data) + .frame(maxWidth: .infinity) + .frame(height: 160) + Text("Intensity \(Int((intensity * 100).rounded()))%") + .font(Theme.mono(12)).foregroundColor(Theme.accent) + HorizontalSlider(value: intensity) { model.set("intensity", Swift.min(Swift.max($0, 0), 1)) } + .frame(maxWidth: .infinity) + .frame(height: 40) + Text("Low = occasional stutters · High = constant glitch & octave jumps.") + .font(Theme.mono(10)).foregroundColor(Theme.dim) + .multilineTextAlignment(.center) + .frame(maxWidth: .infinity) + } + } +} + +/// The scope, polled from the data source once per display frame. +private struct GranularScope: View { + let data: DeviceDataSource? + private static let capacity = 128 // the effect fills up to its own scope size (96) + + var body: some View { + TimelineView(.animation) { _ in + let scope = data?.effectScope(capacity: Self.capacity) + ZStack { + Canvas { ctx, size in draw(scope, in: &ctx, size: size) } + if scope == nil { + Text("Add to a mixer channel's FX and play to see the scope.") + .font(Theme.mono(11)).foregroundColor(Theme.dim) + .multilineTextAlignment(.center) + .padding(.horizontal, 8) + } + } + } + .background(Theme.background) + .overlay(Rectangle().stroke(Theme.grid, lineWidth: 1)) + } + + private func draw(_ scope: (samples: [Float], playhead: Float)?, in ctx: inout GraphicsContext, size: CGSize) { + let w = size.width, h = size.height + let cy = h * 0.5, amp = h * 0.42 + var base = Path() + base.move(to: CGPoint(x: 0, y: cy)) + base.addLine(to: CGPoint(x: w, y: cy)) + ctx.stroke(base, with: .color(Theme.grid), lineWidth: 1) + guard let s = scope, s.samples.count > 1 else { return } + + // Dotted waveform of the signal passing through. + let n = s.samples.count + let step = w / CGFloat(n - 1) + var dots = Path() + for k in 0..= 0 && ph <= 1 { + let px = CGFloat(ph) * w + var line = Path() + line.move(to: CGPoint(x: px, y: 0)) + line.addLine(to: CGPoint(x: px, y: h)) + ctx.stroke(line, with: .color(Theme.accent), lineWidth: 2) + ctx.fill(Path(ellipseIn: CGRect(x: px - 3, y: cy - 3, width: 6, height: 6)), with: .color(Theme.accent)) + } + } +} + +/// A horizontal fill-from-left slider like Android's retro faders: tap or drag to set. +private struct HorizontalSlider: View { + let value: Float + let onChange: (Float) -> Void + + var body: some View { + GeometryReader { geo in + let w = geo.size.width + let frac = CGFloat(Swift.min(Swift.max(value, 0.001), 1)) + ZStack(alignment: .leading) { + Theme.background + HStack(spacing: 0) { + Spacer(minLength: 0) + Theme.accent.frame(width: 3) // thumb + } + .frame(width: Swift.max(w * frac, 3)) + .background(Theme.accent.opacity(0.30)) + } + .overlay(Rectangle().stroke(Theme.grid, lineWidth: 1)) + .contentShape(Rectangle()) + .gesture(DragGesture(minimumDistance: 0).onChanged { g in + if w > 0 { onChange(Float(g.location.x / w)) } + }) + } + } +} + +// MARK: - plugin backend + +/// The effect AU's scope (SizzleEffectAU, channel 0). SizzleEffectAU.h isn't in the +/// Swift bridging headers, so its two methods are declared here and reached by +/// selector; any other device AU doesn't respond and has no scope. +@objc private protocol EffectScopeAU { + func copyEffectScope(_ out: UnsafeMutablePointer, capacity: Int) -> Int + var effectPlayhead: Float { get } +} + +extension AUDataSource { + func effectScope(capacity: Int) -> (samples: [Float], playhead: Float)? { + guard capacity > 0, au.responds(to: #selector(EffectScopeAU.copyEffectScope(_:capacity:))) else { return nil } + let src = unsafeBitCast(au, to: EffectScopeAU.self) + var buf = [Float](repeating: 0, count: capacity) + let n = buf.withUnsafeMutableBufferPointer { src.copyEffectScope($0.baseAddress!, capacity: $0.count) } + guard n >= 0 else { return nil } + return (Array(buf.prefix(n)), src.effectPlayhead) + } } diff --git a/ios/app/FX/Editor/Bespoke/MixTightenerBespoke.swift b/ios/app/FX/Editor/Bespoke/MixTightenerBespoke.swift index c379ee5..a7d2948 100644 --- a/ios/app/FX/Editor/Bespoke/MixTightenerBespoke.swift +++ b/ios/app/FX/Editor/Bespoke/MixTightenerBespoke.swift @@ -3,8 +3,96 @@ import SwiftUI -/// The MixTightener's hand-built editor parts (stub: card layout until ported). +/// The Mix Tightener's hand-built editor (Android's MixTightenerEditor): four +/// vertical faders, bottom = off, top = full. +/// - Strength: the master amount of the EQ → compressor → limiter chain (a parameter). +/// - EQ / Comp / Limit: per-stage trims (`eqAmt`, `compAmt`, `limAmt`). They aren't +/// ParamSpecs, so they go through the data source's hidden values (song slot or AU +/// state); each stage's amount in the DSP is Strength × its trim. A missing trim +/// reads as 1, like MixTightener.cpp. @MainActor enum MixTightenerBespoke { - static func body(_ model: DeviceModel) -> AnyView? { nil } + static func body(_ model: DeviceModel) -> AnyView? { AnyView(MixTightenerEditorView(model: model)) } + + static let trims: Set = ["eqAmt", "compAmt", "limAmt"] + + /// A trim's value (0..1). AUDataSource doesn't forward hidden values yet, so the + /// AU is asked directly. + static func trim(_ model: DeviceModel, _ key: String) -> Float { + let text: String? + if let au = (model.data as? AUDataSource)?.au { text = au.hiddenValue(forKey: key) } + else { text = model.data?.hiddenValue(key) } + return Swift.min(1, Swift.max(0, text.flatMap { Float($0.trimmingCharacters(in: .whitespaces)) } ?? 1)) + } + + static func setTrim(_ model: DeviceModel, _ key: String, _ v: Float) { + let text = String(Swift.min(1, Swift.max(0, v))) + if let au = (model.data as? AUDataSource)?.au { au.setHiddenValue(text, forKey: key) } + else { model.data?.setHiddenValue(text, key: key) } + } +} + +private struct MixTightenerEditorView: View { + @ObservedObject var model: DeviceModel + /// Hidden values aren't published by the model: bumped after a trim write so the + /// faders re-read them (presets and parameter changes re-render via the model). + @State private var trimRevision = 0 + + var body: some View { + VStack(spacing: 10) { + Text("Preset-driven EQ → 3-band compressor → limiter. Pick a preset, then set the master Strength and trim each stage:") + .font(Theme.mono(11)).foregroundColor(Theme.dim).multilineTextAlignment(.center) + .fixedSize(horizontal: false, vertical: true) + HStack(spacing: 8) { + fader("strength", "STRENGTH") + fader("eqAmt", "EQ") + fader("compAmt", "COMP") + fader("limAmt", "LIMIT") + } + .frame(height: 268) + Text("Bottom = off · Top = full. Each stage = Strength × its fader.") + .font(Theme.mono(10)).foregroundColor(Theme.dim).multilineTextAlignment(.center) + .fixedSize(horizontal: false, vertical: true) + } + .padding(.top, 4) + .frame(maxWidth: .infinity) + } + + private func fader(_ key: String, _ label: String) -> some View { + let hidden = MixTightenerBespoke.trims.contains(key) + let value = hidden ? MixTightenerBespoke.trim(model, key) : Swift.min(1, Swift.max(0, model.value(key))) + return MixTightenerFader(label: label, value: value) { v in + if hidden { MixTightenerBespoke.setTrim(model, key, v); trimRevision &+= 1 } + else { model.set(key, v) } + } + } +} + +/// One labelled vertical fader: tap or drag to set (absolute position). +private struct MixTightenerFader: View { + let label: String + let value: Float + let onChange: (Float) -> Void + + var body: some View { + VStack(spacing: 4) { + Text(label).font(Theme.mono(11)).foregroundColor(Theme.accent).lineLimit(1).minimumScaleFactor(0.7) + Text("\(Int((value * 100).rounded()))%").font(Theme.mono(12)).foregroundColor(Theme.text) + GeometryReader { g in + let h = g.size.height + let fill = h * CGFloat(Swift.max(0.001, value)) + ZStack(alignment: .bottom) { + Rectangle().fill(Theme.background) + Rectangle().fill(Theme.accent.opacity(0.30)).frame(height: fill) + Rectangle().fill(Theme.accent).frame(height: 3).offset(y: -Swift.max(0, fill - 3)) + } + .overlay(Rectangle().stroke(Theme.grid, lineWidth: 1)) + .contentShape(Rectangle()) + .gesture(DragGesture(minimumDistance: 0).onChanged { d in + onChange(Float(1 - Swift.min(1, Swift.max(0, d.location.y / Swift.max(1, h))))) + }) + } + } + .frame(maxWidth: .infinity) + } } diff --git a/ios/app/FX/Editor/Bespoke/TapeEngineBespoke.swift b/ios/app/FX/Editor/Bespoke/TapeEngineBespoke.swift index 72ea1ca..48cbdcd 100644 --- a/ios/app/FX/Editor/Bespoke/TapeEngineBespoke.swift +++ b/ios/app/FX/Editor/Bespoke/TapeEngineBespoke.swift @@ -3,8 +3,191 @@ import SwiftUI -/// The TapeEngine's hand-built editor parts (stub: card layout until ported). +/// The Tape Engine's hand-built editor (Android's TapeEngineEditor): a reel-to-reel +/// transport, two NAB reels feeding tape under tension down to a playhead block +/// between them, then round knobs for wow, flutter, hiss and the wow's tempo sync. +/// +/// Press and hold a reel to brake the tape. Like Android, the brake is the `speed` +/// parameter: pressing writes 0.5 and releasing writes 1 through DeviceModel.set (an +/// AU parameter in the plugin, the slot's value in the app). TapeEngine.cpp reads +/// `speed` as its target and glides its read rate toward it (SPEED_GLIDE per sample, +/// ≈0.19 s at 44.1 kHz), so the pitch dives and springs back; the reels ease toward +/// the same target at the same pace. @MainActor enum TapeEngineBespoke { - static func body(_ model: DeviceModel) -> AnyView? { nil } + static func body(_ model: DeviceModel) -> AnyView? { AnyView(TapeEngineEditorView(model: model)) } + + static let brakeSpeed: Float = 0.5 // ≈ one octave down while a reel is held + static let minSpeed: Float = 0.25 +} + +/// The transport's geometry and motion constants (Android's TapeEngineEditor). +private enum TapeReel { + static let degPerSecond = 360.0 // one turn a second at full speed + static let glideSeconds = 0.19 // the DSP's speed glide time constant + static let lX: CGFloat = 0.30, rX: CGFloat = 0.70, centreY: CGFloat = 0.38 + static let height: CGFloat = 180 + + static func radius(_ size: CGSize) -> CGFloat { Swift.min(size.height * 0.30, size.width * 0.20) } + + /// Whether [p] is on either reel (the brake's hit area). + static func hit(_ p: CGPoint, _ size: CGSize) -> Bool { + let r = radius(size), cy = size.height * centreY + return hypot(p.x - size.width * lX, p.y - cy) <= r || hypot(p.x - size.width * rX, p.y - cy) <= r + } +} + +/// The reels' angle and a display speed eased toward the target, advanced by wall +/// time on each frame (not published: the TimelineView redraws). +private final class TapeReelClock { + var angle = 0.0 + var speed = 1.0 + private var last: Date? + + func advance(to now: Date, target: Double) -> Double { + let dt = last.map { Swift.min(0.1, Swift.max(0, now.timeIntervalSince($0))) } ?? 0 + last = now + speed += (target - speed) * (1 - exp(-dt / TapeReel.glideSeconds)) + angle = (angle + speed * TapeReel.degPerSecond * dt).truncatingRemainder(dividingBy: 360) + return angle + } +} + +private struct TapeEngineEditorView: View { + @ObservedObject var model: DeviceModel + @State private var clock = TapeReelClock() + @State private var touching = false + @State private var braking = false + + var body: some View { + VStack(spacing: 8) { + transport + Text("Hold a reel to brake the tape — pitch dives, then springs back.") + .font(Theme.mono(11)).foregroundColor(Theme.dim).multilineTextAlignment(.center) + .fixedSize(horizontal: false, vertical: true) + .frame(maxWidth: .infinity) + HStack(alignment: .top, spacing: 6) { + knob("wow", "Wow") + knob("flutter", "Flutter") + knob("hiss", "Hiss") + knob("division", "Wow Sync") + } + .padding(.top, 2) + } + .onDisappear { release() } + } + + private var transport: some View { + let target = Double(Swift.min(1, Swift.max(TapeEngineBespoke.minSpeed, model.value("speed")))) + return GeometryReader { g in + TimelineView(.animation) { tl in + let angle = clock.advance(to: tl.date, target: target) + Canvas { ctx, size in TapeTransportDrawing.draw(ctx, size, angle: angle) } + } + .contentShape(Rectangle()) + .gesture(DragGesture(minimumDistance: 0) + .onChanged { d in + guard !touching else { return } + touching = true + if TapeReel.hit(d.startLocation, g.size) { + braking = true + model.set("speed", TapeEngineBespoke.brakeSpeed) + } + } + .onEnded { _ in release() }) + } + .frame(height: TapeReel.height) + .background(Theme.surface) + } + + private func release() { + touching = false + if braking { braking = false; model.set("speed", 1) } + } + + @ViewBuilder private func knob(_ key: String, _ label: String) -> some View { + if let p = model.params[key] { + KnobView(label: label, valueText: Format.value(p, model.value(key)), value: model.value(key), + min: p.min, max: p.max, def: p.def, tone: Theme.accent) { model.set(key, $0) } + } + } +} + +/// The transport drawing: tape, playhead, then the two reels over it. +private enum TapeTransportDrawing { + static func draw(_ ctx: GraphicsContext, _ size: CGSize, angle: Double) { + let cx0 = size.width * TapeReel.lX, cx1 = size.width * TapeReel.rX + let cy = size.height * TapeReel.centreY + let r = TapeReel.radius(size) + + // Playhead block between and below the reels. + let hw = (cx1 - cx0) * 0.46, hh = size.height * 0.13 + let hx = size.width * 0.5, hy = cy + r + size.height * 0.14 + let tl = CGPoint(x: hx - hw / 2, y: hy - hh / 2), tr = CGPoint(x: hx + hw / 2, y: hy - hh / 2) + + // Tensioned tape: from each reel's bottom straight to the playhead and across its top. + var tape = Path() + tape.move(to: CGPoint(x: cx0, y: cy + r)) + tape.addLine(to: tl); tape.addLine(to: tr) + tape.addLine(to: CGPoint(x: cx1, y: cy + r)) + ctx.stroke(tape, with: .color(Theme.dim), lineWidth: 1.5) + + let head = Path(roundedRect: CGRect(x: tl.x, y: tl.y, width: hw, height: hh), cornerRadius: hh * 0.45) + ctx.fill(head, with: .color(Theme.grid)) + ctx.stroke(head, with: .color(Theme.accent), lineWidth: 1.2) + var gap = Path() + gap.move(to: CGPoint(x: hx, y: hy - hh / 2 + 2)); gap.addLine(to: CGPoint(x: hx, y: hy + hh / 2 - 2)) + ctx.stroke(gap, with: .color(Theme.accent), lineWidth: 1.2) + + reel(ctx, CGPoint(x: cx0, y: cy), r, angle) + reel(ctx, CGPoint(x: cx1, y: cy), r, angle) + } + + /// One NAB reel: metal flange, three rotating rounded-trapezoid bobbin holes, the hub. + private static func reel(_ ctx: GraphicsContext, _ c: CGPoint, _ r: CGFloat, _ angle: Double) { + ctx.fill(circle(c, r), with: .color(Theme.grid)) + var holes = Path() + for k in 0..<3 { holes.addPath(bobbinHole(c, r, angle + Double(k) * 120)) } + ctx.fill(holes, with: .color(Theme.surface)) + ctx.fill(circle(c, r * 0.26), with: .color(Theme.surface)) + ctx.stroke(circle(c, r * 0.26), with: .color(Theme.accent), lineWidth: 1.6) + ctx.stroke(circle(c, r * 0.14), with: .color(Theme.accent), lineWidth: 1.1) + ctx.stroke(circle(c, r), with: .color(Theme.dim), lineWidth: 1.4) + } + + private static func circle(_ c: CGPoint, _ r: CGFloat) -> Path { + Path(ellipseIn: CGRect(x: c.x - r, y: c.y - r, width: r * 2, height: r * 2)) + } + + /// A hole at [deg] around the reel: wide toward the hub, narrow toward the rim. + private static func bobbinHole(_ c: CGPoint, _ r: CGFloat, _ deg: Double) -> Path { + let rIn = r * 0.40, rOut = r * 0.86 + let v = [polar(c, rIn, deg - 44), polar(c, rOut, deg - 13), polar(c, rOut, deg + 13), polar(c, rIn, deg + 44)] + return roundedPoly(v, corner: r * 0.09) + } + + /// A closed polygon through [v] with every corner rounded to [corner]. + private static func roundedPoly(_ v: [CGPoint], corner: CGFloat) -> Path { + var p = Path() + let n = v.count + for i in 0.. CGPoint { + let dx = to.x - from.x, dy = to.y - from.y + let d = Swift.max(1e-3, hypot(dx, dy)) + return CGPoint(x: from.x + dx / d * len, y: from.y + dy / d * len) + } + + private static func polar(_ c: CGPoint, _ rad: CGFloat, _ deg: Double) -> CGPoint { + let a = deg * .pi / 180 + return CGPoint(x: c.x + rad * CGFloat(cos(a)), y: c.y + rad * CGFloat(sin(a))) + } } diff --git a/ios/app/FX/Editor/Bespoke/WavetableBespoke.swift b/ios/app/FX/Editor/Bespoke/WavetableBespoke.swift index 6e1f748..7f4866d 100644 --- a/ios/app/FX/Editor/Bespoke/WavetableBespoke.swift +++ b/ios/app/FX/Editor/Bespoke/WavetableBespoke.swift @@ -2,10 +2,162 @@ // SPDX-License-Identifier: GPL-3.0-or-later import SwiftUI +import UniformTypeIdentifiers -/// The Wavetable's table drawing and LOAD TABLE (stub until ported). +/// The Wavetable's own pieces inside its generic cards (Android's WavetableEditor.kt): +/// each oscillator card draws that oscillator's table, and Oscillator 1's card +/// carries LOAD TABLE, because a loaded WAV becomes the "Custom" table and is +/// selected on oscillator 1. @MainActor enum WavetableBespoke { - static func preview(osc: Int, tone: Color, model: DeviceModel) -> AnyView? { nil } - static func loadTableAction(tone: Color, model: DeviceModel) -> AnyView? { nil } + static func preview(osc: Int, tone: Color, model: DeviceModel) -> AnyView? { + AnyView(WavetablePreview(osc: osc, tone: tone, model: model)) + } + static func loadTableAction(tone: Color, model: DeviceModel) -> AnyView? { + AnyView(LoadTableAction(model: model)) + } + + /// What the preview draws of a table: up to 16 of its frames, 128 points each. + struct Curves { + let frames: Int + let rows: [(points: [Float], frame: Int)] + } + + /// Curves by table (a factory name, or a custom sample id + frame length): + /// tables are immutable once built, so each is read and thinned out once. + private static var cache: [String: Curves] = [:] + + static func curves(key: String, osc: Int, data: DeviceDataSource?) -> Curves? { + if let c = cache[key] { return c } + guard let t = data?.wavetableFrames(osc: osc), t.frames > 0, t.size >= 128, + t.data.count >= t.frames * t.size else { return nil } + let n = t.size, step = Swift.max(1, t.frames / 16) + let rows = stride(from: 0, to: t.frames, by: step).map { f -> (points: [Float], frame: Int) in + ((0..<128).map { i in t.data[f * n + i * n / 128] }, f) + } + let c = Curves(frames: t.frames, rows: rows) + if cache.count > 64 { cache.removeAll() } + cache[key] = c + return c + } + + /// The table oscillator [osc] plays, and the key its curves are cached under. + static func tableKey(osc: Int, model: DeviceModel) -> (name: String, custom: Bool, key: String) { + let name = model.choice("o\(osc)table") + guard name == "Custom" else { return (name, false, "F|" + name) } + let id = model.data?.hiddenValue("sfSample") ?? "" + return (name, true, "C|\(id)|\(model.choice("wtframe"))") + } + + /// Native floats from a bridge call's bytes. + static func floats(_ d: Data) -> [Float] { d.withUnsafeBytes { Array($0.bindMemory(to: Float.self)) } } +} + +/// Every frame of oscillator [osc]'s table stacked back to front, the one at its POSITION lit. +struct WavetablePreview: View { + let osc: Int + let tone: Color + @ObservedObject var model: DeviceModel + /// Bumped while the table is being built, to look again. + @State private var retry = 0 + + var body: some View { + let (name, custom, key) = WavetableBespoke.tableKey(osc: osc, model: model) + let curves = WavetableBespoke.curves(key: key, osc: osc, data: model.data) + let unloaded = custom && model.data?.hiddenValue("sfSample") == nil + let caption = curves.map { "\(custom ? "your table" : name) · \($0.frames) frames" } + ?? (unloaded ? "Custom · no table loaded" : "\(name) (preparing…)") + let pos = model.value("o\(osc)pos") + ZStack(alignment: .topLeading) { + if let c = curves { + Canvas { ctx, size in draw(c, pos: pos, in: ctx, size: size) } + } + Text(caption).font(Theme.mono(9)).foregroundColor(Theme.dim) + .padding(.horizontal, 4).padding(.vertical, 2) + } + .frame(maxWidth: .infinity, minHeight: 72, maxHeight: 72) + .background(Theme.background) + .overlay(Rectangle().stroke(Theme.grid, lineWidth: 1)) + .task(id: retry) { + guard curves == nil, !unloaded, retry < 60 else { return } + try? await Task.sleep(nanoseconds: 300_000_000) + retry += 1 + } + } + + private func draw(_ c: WavetableBespoke.Curves, pos: Float, in ctx: GraphicsContext, size: CGSize) { + let k = c.rows.count + let rowH = size.height * 0.45 + let lit = Int(pos * Float(c.frames - 1) + 0.5) + let near = Swift.max(1, c.frames / k) + let w = size.width * 0.76 + for idx in stride(from: k - 1, through: 0, by: -1) { + let row = c.rows[idx] + let depth = k > 1 ? CGFloat(idx) / CGFloat(k - 1) : 0 + let x0 = size.width * 0.04 + depth * size.width * 0.18 + let yMid = size.height * 0.72 - depth * size.height * 0.45 + let on = abs(row.frame - lit) * 2 <= near + let n = row.points.count + var path = Path() + for i in 0.. (frames: Int, size: Int, data: [Float])? { + guard let p = au.parameterTree?.allParameters.first(where: { $0.identifier == "o\(osc)table" }), + let names = p.valueStrings, !names.isEmpty else { return nil } + let name = names[Swift.max(0, Swift.min(names.count - 1, Int(p.value.rounded())))] + var frames = 0, size = 0 + guard let d = SizzleDeviceAU.factoryWavetable(named: name, blocking: Snapshot.active, frames: &frames, size: &size) + else { return nil } + return (frames, size, WavetableBespoke.floats(d)) + } } diff --git a/ios/app/FX/Editor/DeviceModel.swift b/ios/app/FX/Editor/DeviceModel.swift index f8b6679..3885ded 100644 --- a/ios/app/FX/Editor/DeviceModel.swift +++ b/ios/app/FX/Editor/DeviceModel.swift @@ -82,6 +82,9 @@ final class DeviceModel: ObservableObject { if let tree = au.parameterTree, let t = token { cleanup = { tree.removeParameterObserver(t) } } } + /// Set the data source and return self (for builders). + func withData(_ source: DeviceDataSource) -> DeviceModel { data = source; return self } + func value(_ key: String) -> Float { values[key] ?? params[key]?.def ?? 0 } func set(_ key: String, _ v: Float) { diff --git a/ios/app/FX/SizzleDeviceAU+Sources.h b/ios/app/FX/SizzleDeviceAU+Sources.h new file mode 100644 index 0000000..7b445a1 --- /dev/null +++ b/ios/app/FX/SizzleDeviceAU+Sources.h @@ -0,0 +1,30 @@ +// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown +// SPDX-License-Identifier: GPL-3.0-or-later + +#import "SizzleDeviceAU.h" + +NS_ASSUME_NONNULL_BEGIN + +/// What the Wavetable's and the Grain Cloud's editors draw in a plug-in: the +/// built-in tables and sources (made in code, no sample store needed). Custom +/// tables and sources need the Sizzle app's sample store for now. +@interface SizzleDeviceAU (Sources) + +/// Factory wavetable [name], level 0 ([frames] x [size] floats), or nil while the +/// factory set isn't built: building then starts in the background (ask again), or, +/// with [blocking], happens now on this thread (the Mac snapshot tools). ++ (nullable NSData *)factoryWavetableNamed:(NSString *)name blocking:(BOOL)blocking + frames:(NSInteger *)frames size:(NSInteger *)size + NS_SWIFT_NAME(factoryWavetable(named:blocking:frames:size:)); + +/// Peak envelope (|x| max per bucket, 0..1, [buckets] floats) of the Grain Cloud's +/// built-in source [name], or nil (unknown, or not rendered yet: as above). ++ (nullable NSData *)grainSourcePeaksNamed:(NSString *)name buckets:(NSInteger)buckets blocking:(BOOL)blocking + NS_SWIFT_NAME(grainSourcePeaks(named:buckets:blocking:)); + +/// Length in seconds of built-in source [name], or 0 while it isn't rendered. ++ (double)grainSourceSecondsNamed:(NSString *)name NS_SWIFT_NAME(grainSourceSeconds(named:)); + +@end + +NS_ASSUME_NONNULL_END diff --git a/ios/app/FX/SizzleDeviceAU+Sources.mm b/ios/app/FX/SizzleDeviceAU+Sources.mm new file mode 100644 index 0000000..6c74de9 --- /dev/null +++ b/ios/app/FX/SizzleDeviceAU+Sources.mm @@ -0,0 +1,66 @@ +// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown +// SPDX-License-Identifier: GPL-3.0-or-later + +#import "SizzleDeviceAU+Sources.h" + +#include +#include +#include "echofield/GrainSources.hpp" +#include "wavetable/WaveTables.hpp" + +using namespace sizzle; +namespace WaveTables = wavetable::WaveTables; +namespace GrainSources = echofield::GrainSources; + +@implementation SizzleDeviceAU (Sources) + ++ (nullable NSData *)factoryWavetableNamed:(NSString *)name blocking:(BOOL)blocking + frames:(NSInteger *)frames size:(NSInteger *)size { + const char *n = name.UTF8String ?: ""; + if (WaveTables::factoryIndex(n) < 0) return nil; + const wavetable::WaveTable *t = WaveTables::factory(n); + if (!t) { + if (blocking) WaveTables::prewarmBlocking(); else WaveTables::prewarm(); + t = WaveTables::factory(n); + } + if (!t) return nil; + int len = t->size(0); + if (frames) *frames = t->frames; + if (size) *size = len; + return [NSData dataWithBytes:t->data(0) length:(NSUInteger)t->frames * (NSUInteger)len * sizeof(float)]; +} + +static const Sample *builtInSource(NSString *name, BOOL blocking) { + const char *n = name.UTF8String ?: ""; + if (GrainSources::indexOf(n) < 0) return nullptr; + const Sample *s = GrainSources::get(n); + if (!s) { + if (blocking) GrainSources::prewarmBlocking(); else GrainSources::prewarm(); + s = GrainSources::get(n); + } + return s; +} + ++ (nullable NSData *)grainSourcePeaksNamed:(NSString *)name buckets:(NSInteger)buckets blocking:(BOOL)blocking { + const Sample *s = builtInSource(name, blocking); + if (!s || s->data.empty() || buckets <= 0) return nil; + size_t n = s->data.size(); + const float *x = s->data.data(); + NSMutableData *d = [NSMutableData dataWithLength:(NSUInteger)buckets * sizeof(float)]; + float *out = (float *)d.mutableBytes; + for (NSInteger b = 0; b < buckets; ++b) { + size_t a = n * (size_t)b / (size_t)buckets; + size_t e = std::max(a + 1, n * (size_t)(b + 1) / (size_t)buckets); + float m = 0.f; + for (size_t i = a; i < e && i < n; ++i) m = std::max(m, std::fabs(x[i])); + out[b] = std::min(m, 1.f); + } + return d; +} + ++ (double)grainSourceSecondsNamed:(NSString *)name { + const Sample *s = builtInSource(name, NO); + return s && s->sampleRate > 0 ? (double)s->data.size() / s->sampleRate : 0; +} + +@end diff --git a/ios/app/FX/SizzleEffectAU.h b/ios/app/FX/SizzleEffectAU.h index 357d921..bc91004 100644 --- a/ios/app/FX/SizzleEffectAU.h +++ b/ios/app/FX/SizzleEffectAU.h @@ -8,6 +8,14 @@ NS_ASSUME_NONNULL_BEGIN /// One Sizzle audio effect as an AUv3 (`aufx`): a C++ `sizzle::Effect` per channel /// (the effects are mono, as in Sizzle's mixer: stereo runs dual mono). @interface SizzleEffectAU : SizzleDeviceAU + +/// The live scope of the effect on channel 0 (Kotlin's VizEffect): copies up to +/// [capacity] samples, oldest to newest, into [out] and returns the count, or -1 +/// when the effect has no scope or render resources aren't allocated. Any thread. +- (NSInteger)copyEffectScope:(float *)out capacity:(NSInteger)capacity; +/// Its read head within the scope window, 0 (oldest) to 1 (newest), or -1. +@property (nonatomic, readonly) float effectPlayhead; + @end NS_ASSUME_NONNULL_END diff --git a/ios/app/FX/SizzleEffectAU.mm b/ios/app/FX/SizzleEffectAU.mm index c9b03ef..b72c79b 100644 --- a/ios/app/FX/SizzleEffectAU.mm +++ b/ios/app/FX/SizzleEffectAU.mm @@ -6,6 +6,7 @@ #import #include +#include #include #include "sizzle/Effect.hpp" @@ -18,6 +19,9 @@ struct EffectKernel final : DeviceKernel { int channels = 0; std::atomic bypass{false}; std::vector inBuf[2]; + /// Held by the editor's scope reads and by (de)allocation, which replace fx[]: + /// never by the render thread, so the audio path stays lock-free. + std::mutex vizLock; void apply(const Params &p, float tempoBpm) override { for (int c = 0; c < channels; ++c) fx[c]->update(p, tempoBpm); @@ -72,9 +76,12 @@ struct EffectKernel final : DeviceKernel { EffectKernel *k = self.fxKernel; int sr = (int)std::lround(_outBus.format.sampleRate); k->channels = (int)chOut; - for (int c = 0; c < 2; ++c) { - k->fx[c] = c < k->channels ? Effect::create(k->type.c_str(), sr) : nullptr; - k->inBuf[c].assign(self.maximumFramesToRender, 0.f); + { + std::lock_guard g(k->vizLock); + for (int c = 0; c < 2; ++c) { + k->fx[c] = c < k->channels ? Effect::create(k->type.c_str(), sr) : nullptr; + k->inBuf[c].assign(self.maximumFramesToRender, 0.f); + } } if (!k->fx[0]) { if (outError) *outError = [NSError errorWithDomain:NSOSStatusErrorDomain code:kAudioUnitErr_FailedInitialization userInfo:nil]; @@ -85,10 +92,27 @@ struct EffectKernel final : DeviceKernel { } - (void)deallocateRenderResources { - for (auto &f : self.fxKernel->fx) f.reset(); + { + std::lock_guard g(self.fxKernel->vizLock); + for (auto &f : self.fxKernel->fx) f.reset(); + } [super deallocateRenderResources]; } +- (NSInteger)copyEffectScope:(float *)out capacity:(NSInteger)capacity { + EffectKernel *k = self.fxKernel; + std::lock_guard g(k->vizLock); + Effect *fx = k->fx[0].get(); + return fx && fx->hasScope() ? fx->copyScope(out, (int)capacity) : -1; +} + +- (float)effectPlayhead { + EffectKernel *k = self.fxKernel; + std::lock_guard g(k->vizLock); + Effect *fx = k->fx[0].get(); + return fx && fx->hasScope() ? fx->playhead() : -1.f; +} + - (AUInternalRenderBlock)internalRenderBlock { EffectKernel *k = self.fxKernel; return ^AUAudioUnitStatus(AudioUnitRenderActionFlags *actionFlags, const AudioTimeStamp *timestamp, diff --git a/ios/app/Host/Bespoke/SlotDataSource+Sources.swift b/ios/app/Host/Bespoke/SlotDataSource+Sources.swift new file mode 100644 index 0000000..b3b8212 --- /dev/null +++ b/ios/app/Host/Bespoke/SlotDataSource+Sources.swift @@ -0,0 +1,44 @@ +// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown +// SPDX-License-Identifier: GPL-3.0-or-later + +import Foundation + +/// The Wavetable's tables and the Grain Cloud's sources for a toolbox slot of the +/// song, and loading your own (SizzleSession+Sources). +extension SlotDataSource: SampleLengthSource { + func wavetableFrames(osc: Int) -> (frames: Int, size: Int, data: [Float])? { + var frames = 0, size = 0 + guard let d = session.wavetable(ofSlot: slot, osc: osc, frames: &frames, size: &size) else { return nil } + return (frames, size, WavetableBespoke.floats(d)) + } + + func samplePeaks(key: String, buckets: Int) -> [Float]? { + session.samplePeaks(ofSlot: slot, key: key, buckets: buckets).map(WavetableBespoke.floats) + } + + func sampleSeconds(key: String) -> Double? { + let s = session.sampleSeconds(ofSlot: slot, key: key) + return s > 0 ? s : nil + } + + /// "wavetable" (LOAD TABLE) or "grainSource" (the Grain Cloud's LOAD WAV): the + /// picked file (security-scoped, at most 64 MB) into this slot. + func loadFile(_ url: URL, kind: String) -> String? { + guard kind == "wavetable" || kind == "grainSource" else { return "Not available here yet." } + let scoped = url.startAccessingSecurityScopedResource() + defer { if scoped { url.stopAccessingSecurityScopedResource() } } + let maxBytes = 64 * 1024 * 1024 + let size = (try? url.resourceValues(forKeys: [.fileSizeKey]).fileSize) ?? 0 + guard size <= maxBytes, let data = try? Data(contentsOf: url), data.count <= maxBytes else { + return "Couldn't read the file, or it's larger than 64 MB." + } + let name = url.deletingPathExtension().lastPathComponent + do { + if kind == "wavetable" { try session.loadWavetableData(data, name: name, intoSlot: slot) } + else { try session.loadGrainSourceData(data, name: name, intoSlot: slot) } + return nil + } catch { + return error.localizedDescription + } + } +} diff --git a/ios/app/Host/Bespoke/SlotDataSource+Viz.swift b/ios/app/Host/Bespoke/SlotDataSource+Viz.swift new file mode 100644 index 0000000..4c8def6 --- /dev/null +++ b/ios/app/Host/Bespoke/SlotDataSource+Viz.swift @@ -0,0 +1,18 @@ +// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown +// SPDX-License-Identifier: GPL-3.0-or-later + +import Foundation + +/// The live effect scope of a song slot (the Granular Glitch's), straight from the +/// engine's channel chains: nil until the slot sits on a mixer channel's FX. +extension SlotDataSource { + func effectScope(capacity: Int) -> (samples: [Float], playhead: Float)? { + guard capacity > 0 else { return nil } + var buf = [Float](repeating: 0, count: capacity) + let n = buf.withUnsafeMutableBufferPointer { p in + session.copyEffectScope(ofSlot: slot, into: p.baseAddress!, capacity: p.count) + } + guard n >= 0 else { return nil } + return (Array(buf.prefix(n)), session.effectPlayhead(ofSlot: slot)) + } +} diff --git a/ios/app/Host/Bridging.h b/ios/app/Host/Bridging.h index f0dcc48..1b9f8ae 100644 --- a/ios/app/Host/Bridging.h +++ b/ios/app/Host/Bridging.h @@ -1,6 +1,7 @@ #import "ObjC/SPKTry.h" #import "SizzleHost.h" #import "SizzleFXViewController.h" +#import "SizzleDeviceAU+Sources.h" #import "SizzleSession.h" #import "SizzleSession+Tracker.h" #import "SizzleSession+Mix.h" diff --git a/ios/app/Host/Screens/Toolbox/SlotEditor.swift b/ios/app/Host/Screens/Toolbox/SlotEditor.swift index d404139..885c243 100644 --- a/ios/app/Host/Screens/Toolbox/SlotEditor.swift +++ b/ios/app/Host/Screens/Toolbox/SlotEditor.swift @@ -25,10 +25,11 @@ struct SlotEditor: View { /// the presentation binding before calling the completion handler. @State private var importing: ImportKind? @State private var pickerShown = false + @State private var deviceCallback: ((URL) -> Void)? @State private var importError: String? enum ImportKind: Identifiable { - case preset, padSample, soundFont + case preset, padSample, soundFont, device // device: a bespoke view's own load (deviceFilePicker) var id: Self { self } } @@ -65,7 +66,8 @@ struct SlotEditor: View { } .background(Theme.background.opacity(0.96)) .fileImporter(isPresented: $pickerShown, allowedContentTypes: importTypes, allowsMultipleSelection: false) { result in - if case .success(let urls) = result, let url = urls.first, let kind = importing { load(url, kind) } + guard case .success(let urls) = result, let url = urls.first, let kind = importing else { return } + if kind == .device { deviceCallback?(url) } else { load(url, kind) } } .alert("Import failed", isPresented: Binding(get: { importError != nil }, set: { if !$0 { importError = nil } }), actions: { Button("OK") { importError = nil } }, message: { Text(importError ?? "") }) @@ -97,6 +99,11 @@ struct SlotEditor: View { // The card editor brings its own padding and header row; with no name and // no preset menu (the bar above has them) the row is empty, so pull it up. DeviceEditor(model: model, showsHeader: false).padding(.horizontal, -10) + .environment(\.deviceFilePicker) { done in + deviceCallback = done + importing = .device + pickerShown = true + } .frame(minHeight: 0, maxHeight: .infinity, alignment: .top).clipped() if type == "LFO" { LfoTargetPicker(lfo: slot) } } @@ -108,7 +115,7 @@ struct SlotEditor: View { private var importTypes: [UTType] { switch importing { case .padSample: return [.audio, .wav] - case .preset, .soundFont, .none: return [.item] + case .preset, .soundFont, .device, .none: return [.item] } } @@ -144,6 +151,8 @@ struct SlotEditor: View { if (try? session.loadSampleData(data, name: name, intoSlot: slot, pad: 0)) == nil { importError = "Couldn't load this instrument. Supported formats are .sf2, .xi and uncompressed .wav." } + case .device: + break // handed to the bespoke view (deviceCallback) } } @@ -175,6 +184,7 @@ struct SlotEditor: View { }, applyPreset: { name in _ = session.loadPreset(name, intoSlot: slot) }, reread: read) + .withData(SlotDataSource(session: session, slot: slot)) } } diff --git a/ios/app/Host/SizzleSession+Sources.h b/ios/app/Host/SizzleSession+Sources.h index a151210..4e4d0a9 100644 --- a/ios/app/Host/SizzleSession+Sources.h +++ b/ios/app/Host/SizzleSession+Sources.h @@ -5,8 +5,38 @@ NS_ASSUME_NONNULL_BEGIN -/// API for the device editors' Sources views beyond SizzleSession.h. +/// The Wavetable's and the Grain Cloud's own sounds (AppViewModel.loadWavetable / +/// loadGrainSample) and what their editors draw of them. +/// +/// Custom wavetables: the WAV is kept like any other sample (sample store and +/// Documents/samples/.wav, the slot's `sfSample`), and its table is built off +/// the audio thread: right after a load, and whenever the song changes and a +/// Wavetable slot plays a Custom table that isn't built yet (a loaded song, a new +/// frame length). The audio thread only ever finds a built table or none (silent). @interface SizzleSession (Sources) + +/// A wavetable WAV (Serum's, WaveEdit's or power-of-two frames) becomes Wavetable +/// [slot]'s Custom table: `sfSample` = the stored sample, `wtframe` = the detected +/// frame length (or Auto), `o1table` = Custom. The table is built in the background. +- (BOOL)loadWavetableData:(NSData *)data name:(NSString *)name intoSlot:(NSInteger)slot error:(NSError **)error; + +/// A WAV (or an SF2/XI's sample) becomes Grain Cloud [slot]'s own source +/// (`sfSample`, `source` = Custom). +- (BOOL)loadGrainSourceData:(NSData *)data name:(NSString *)name intoSlot:(NSInteger)slot error:(NSError **)error; + +/// Oscillator [osc]'s table of Wavetable [slot], level 0: [frames] x [size] floats. +/// Nil while it isn't built (a Custom table is then built in the background; ask again). +- (nullable NSData *)wavetableOfSlot:(NSInteger)slot osc:(NSInteger)osc + frames:(NSInteger *)frames size:(NSInteger *)size; + +/// Peak envelope (|x| max per bucket, 0..1, [buckets] floats) of the sample [slot]'s +/// setting [key] names: a Grain Cloud's `source` (a built-in source, or with Custom +/// its own sample), otherwise a sample id (`sfSample`, `padN`). Nil while it has none. +- (nullable NSData *)samplePeaksOfSlot:(NSInteger)slot key:(NSString *)key buckets:(NSInteger)buckets; + +/// Length in seconds of that same sample, or 0. +- (double)sampleSecondsOfSlot:(NSInteger)slot key:(NSString *)key; + @end NS_ASSUME_NONNULL_END diff --git a/ios/app/Host/SizzleSession+Sources.mm b/ios/app/Host/SizzleSession+Sources.mm index 58f69a9..00c5d71 100644 --- a/ios/app/Host/SizzleSession+Sources.mm +++ b/ios/app/Host/SizzleSession+Sources.mm @@ -4,7 +4,279 @@ #import "SizzleSession+Sources.h" #import "SizzleSession+Internal.h" +#include +#include +#include +#include +#include +#include +#include +#include "echofield/EchofieldDefs.hpp" +#include "echofield/GrainSources.hpp" +#include "sampler/SoundFontLoader.hpp" +#include "wavetable/WaveDefs.hpp" +#include "wavetable/WaveTables.hpp" + using namespace sizzle; +using wavetable::WaveTable; +namespace WaveTables = wavetable::WaveTables; +namespace WaveDefs = wavetable::WaveDefs; + +// Defined in SizzleSession.mm (Documents/samples/.wav). +@interface SizzleSession (SourcesPrivate) +- (NSURL *)sampleURL:(const std::string &)id; +@end + +namespace { + +/// The store WaveTables' SampleSource reads (the session's; it lives for the whole app). +std::atomic gStore{nullptr}; + +/// WaveTables::SampleSource: a copy of sample [id]'s data from the store (pinned while copied). +bool storeSource(const char *id, std::vector &out) { + sampler::SampleStore *store = gStore.load(); + const Sample *s = store ? store->get(id) : nullptr; + if (!s) return false; + sampler::SampleStore::pin(s); + out = s->data; + sampler::SampleStore::unpin(s); + return true; +} + +/// Where custom tables are built (one at a time, never the audio thread). +dispatch_queue_t builderQueue() { + static dispatch_queue_t q; + static dispatch_once_t once; + dispatch_once(&once, ^{ + q = dispatch_queue_create("sizzle.wavetables", dispatch_queue_attr_make_with_qos_class(DISPATCH_QUEUE_SERIAL, QOS_CLASS_UTILITY, 0)); + }); + return q; +} + +NSError *sourcesError(NSString *msg) { + return [NSError errorWithDomain:@"Sizzle" code:1 userInfo:@{NSLocalizedDescriptionKey: msg}]; +} + +/// WaveVoice's frame length: wtframe's choice ("Auto" or unknown -> 0). +int frameLenOf(const model::ToolboxSlot &slot) { + const char *v = slot.s("wtframe", WaveDefs::FRAME_SIZES[0]); + for (int i = 1; i < WaveDefs::FRAME_SIZE_COUNT; ++i) + if (!std::strcmp(v, WaveDefs::FRAME_SIZES[i])) return std::atoi(WaveDefs::FRAME_SIZES[i]); + return 0; +} + +bool playsCustom(const model::ToolboxSlot &slot) { + return slot.type == "WAVETABLE" && *slot.s(WaveDefs::SAMPLE_KEY, "") && + (!std::strcmp(slot.s("o1table", ""), WaveTables::CUSTOM) || !std::strcmp(slot.s("o2table", ""), WaveTables::CUSTOM)); +} + +/// |x| max per bucket, 0..1, the buckets spread evenly over the sample. +NSData *peaksOf(const float *x, size_t n, NSInteger buckets) { + if (!x || n == 0 || buckets <= 0) return nil; + NSMutableData *d = [NSMutableData dataWithLength:(NSUInteger)buckets * sizeof(float)]; + float *out = (float *)d.mutableBytes; + for (NSInteger b = 0; b < buckets; ++b) { + size_t a = n * (size_t)b / (size_t)buckets; + size_t e = std::max(a + 1, n * (size_t)(b + 1) / (size_t)buckets); + float m = 0.f; + for (size_t i = a; i < e && i < n; ++i) m = std::max(m, std::fabs(x[i])); + out[b] = std::min(m, 1.f); + } + return d; +} + +/// A sample id from the file's name (ASCII, short: WaveTables keys compare 63 bytes). +std::string newSampleId(NSString *name) { + std::string base; + for (const char *c = name.UTF8String ?: ""; *c && base.size() < 16; ++c) + if ((*c >= 'a' && *c <= 'z') || (*c >= 'A' && *c <= 'Z') || (*c >= '0' && *c <= '9') || *c == '-' || *c == '_') base += *c; + if (base.empty()) base = "source"; + return base + "#" + NSUUID.UUID.UUIDString.UTF8String; +} + +} // namespace @implementation SizzleSession (Sources) + +/// Install the custom-table source and build what songs ask for as they change +/// (a loaded song, a new frame length). Runs at image load; the session itself +/// arrives with its first change notification (posted from init when it loads the +/// autosave), so nothing here creates it. ++ (void)load { + WaveTables::setSampleSource(&storeSource); + @autoreleasepool { + [NSNotificationCenter.defaultCenter addObserverForName:SizzleSessionDidChange object:nil queue:nil + usingBlock:^(NSNotification *note) { + SizzleSession *s = note.object; + if (![s isKindOfClass:SizzleSession.class]) return; + dispatch_async(dispatch_get_main_queue(), ^{ [s src_scheduleTableScan]; }); + }]; + } +} + +/// Coalesce change notifications (knob drags post many) into one scan. +- (void)src_scheduleTableScan { + static BOOL pending = NO; + if (pending) return; + pending = YES; + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ + pending = NO; + [self src_buildMissingTables]; + }); +} + +/// Every Custom table the song plays that isn't built yet: queue it (WaveTables' +/// request), make sure its sample is in the store, then build on the builder queue. +- (void)src_buildMissingTables { + gStore.store(&[self sampleStore]); + __block std::vector> wants; + [self read:^(const model::Project &p, const engine::Engine &) { + for (auto &slot : p.toolbox) + if (playsCustom(slot)) wants.emplace_back(slot.s(WaveDefs::SAMPLE_KEY, ""), frameLenOf(slot)); + }]; + std::vector> missing; + for (auto &w : wants) + if (!WaveTables::forSample(w.first.c_str(), w.second)) missing.emplace_back(w.first, [self sampleURL:w.first]); + if (missing.empty()) return; + sampler::SampleStore *store = &[self sampleStore]; + dispatch_async(builderQueue(), ^{ + for (auto &m : missing) { + if (store->get(m.first.c_str())) continue; + NSData *d = [NSData dataWithContentsOfURL:m.second]; + if (!d) continue; + if (auto s = sampler::SampleStore::decodeWav((const uint8_t *)d.bytes, d.length)) store->put(m.first, std::move(*s)); + } + WaveTables::buildRequested(); + }); +} + +/// Keep [sample] as one of the song's samples (Documents/samples + the store); its id. +- (std::string)src_keepSample:(Sample &)sample name:(NSString *)name { + std::string id = newSampleId(name); + std::vector wav = sampler::SampleStore::encodeWav(sample); + [[NSData dataWithBytes:wav.data() length:wav.size()] writeToURL:[self sampleURL:id] atomically:YES]; + [self sampleStore].put(id, std::move(sample)); + return id; +} + +- (BOOL)loadWavetableData:(NSData *)data name:(NSString *)name intoSlot:(NSInteger)slot error:(NSError **)error { + if (slot < 0 || slot >= model::Project::TOOLBOX_SLOTS || ![[self typeOfSlot:slot] isEqualToString:@"WAVETABLE"]) { + if (error) *error = sourcesError(@"Pick a Wavetable slot."); + return NO; + } + const uint8_t *bytes = (const uint8_t *)data.bytes; + std::optional sample = sampler::SampleStore::decodeWav(bytes, data.length); + if (!sample || sample->data.size() < 64) { + if (error) *error = sourcesError(@"Couldn't load this wavetable. Use an uncompressed .wav (Serum, WaveEdit, or frames of 256–2048 samples)."); + return NO; + } + int detected = WaveTables::detectFrameLength(bytes, data.length, (int)sample->data.size()); + std::string label = WaveDefs::FRAME_SIZES[0]; + for (int i = 1; i < WaveDefs::FRAME_SIZE_COUNT; ++i) + if (std::to_string(detected) == WaveDefs::FRAME_SIZES[i]) label = WaveDefs::FRAME_SIZES[i]; + int frameLen = label == WaveDefs::FRAME_SIZES[0] ? 0 : detected; + gStore.store(&[self sampleStore]); + std::string id = [self src_keepSample:*sample name:name]; + [self edit:^(model::Project &p, engine::Engine &) { + model::ToolboxSlot &s = p.toolbox[(size_t)slot]; + s.set(WaveDefs::SAMPLE_KEY, id.c_str()); + s.set("wtframe", label.c_str()); + s.set("o1table", WaveTables::CUSTOM); + }]; + // Built off the audio thread; until then the oscillator is silent (and asks once). + dispatch_async(builderQueue(), ^{ + if (!WaveTables::forSample(id.c_str(), frameLen)) WaveTables::buildRequested(); + }); + return YES; +} + +- (BOOL)loadGrainSourceData:(NSData *)data name:(NSString *)name intoSlot:(NSInteger)slot error:(NSError **)error { + if (slot < 0 || slot >= model::Project::TOOLBOX_SLOTS || ![[self typeOfSlot:slot] isEqualToString:@"GRAIN_CLOUD"]) { + if (error) *error = sourcesError(@"Pick a Grain Cloud slot."); + return NO; + } + const uint8_t *bytes = (const uint8_t *)data.bytes; + std::optional sample = sampler::SampleStore::decodeWav(bytes, data.length); + if (!sample) { + if (auto l = sampler::SoundFontLoader::load(bytes, data.length)) sample = std::move(l->sample); + } + if (!sample) { + if (error) *error = sourcesError(@"Couldn't load this sound. Supported formats are uncompressed .wav, .sf2 and .xi."); + return NO; + } + std::string id = [self src_keepSample:*sample name:name]; + [self edit:^(model::Project &p, engine::Engine &) { + model::ToolboxSlot &s = p.toolbox[(size_t)slot]; + s.set(echofield::SAMPLE_KEY, id.c_str()); + s.set("source", echofield::CUSTOM); + }]; + return YES; +} + +- (nullable NSData *)wavetableOfSlot:(NSInteger)slot osc:(NSInteger)osc frames:(NSInteger *)frames size:(NSInteger *)size { + if (slot < 0 || slot >= model::Project::TOOLBOX_SLOTS) return nil; + __block std::string table, id; + __block int frameLen = 0; + std::string key = "o" + std::to_string(osc) + "table"; + [self read:^(const model::Project &p, const engine::Engine &) { + const model::ToolboxSlot &s = p.toolbox[(size_t)slot]; + table = s.s(key.c_str(), WaveDefs::TABLES[0]); + id = s.s(WaveDefs::SAMPLE_KEY, ""); + frameLen = frameLenOf(s); + }]; + const WaveTable *t; + if (table == WaveTables::CUSTOM) { + t = WaveTables::forSample(id.c_str(), frameLen); + if (!t && !id.empty()) [self src_scheduleTableScan]; + } else { + t = WaveTables::factory(table.c_str()); + } + if (!t) return nil; + int n = t->size(0); + if (frames) *frames = t->frames; + if (size) *size = n; + return [NSData dataWithBytes:t->data(0) length:(NSUInteger)t->frames * (NSUInteger)n * sizeof(float)]; +} + +/// Run [body] on the sample [slot]'s [key] names (pinned while it runs); NO if none. +- (BOOL)src_withSampleOfSlot:(NSInteger)slot key:(NSString *)key body:(void (^)(const Sample &s))body { + if (slot < 0 || slot >= model::Project::TOOLBOX_SLOTS) return NO; + __block std::string value, id, type; + std::string k = key.UTF8String ?: ""; + [self read:^(const model::Project &p, const engine::Engine &) { + const model::ToolboxSlot &s = p.toolbox[(size_t)slot]; + type = s.type; + value = s.s(k.c_str(), k == "source" ? echofield::SOURCES[0] : ""); + id = s.s(echofield::SAMPLE_KEY, ""); + }]; + if (type == "GRAIN_CLOUD" && k == "source") { + if (value != echofield::CUSTOM) { + const Sample *g = echofield::GrainSources::get(value.c_str()); // built once, never freed + if (g) body(*g); + return g != nullptr; + } + value = id; + } + const Sample *s = [self sampleStore].get(value.c_str()); + if (!s) return NO; + sampler::SampleStore::pin(s); + body(*s); + sampler::SampleStore::unpin(s); + return YES; +} + +- (nullable NSData *)samplePeaksOfSlot:(NSInteger)slot key:(NSString *)key buckets:(NSInteger)buckets { + __block NSData *out = nil; + [self src_withSampleOfSlot:slot key:key body:^(const Sample &s) { out = peaksOf(s.data.data(), s.data.size(), buckets); }]; + return out; +} + +- (double)sampleSecondsOfSlot:(NSInteger)slot key:(NSString *)key { + __block double secs = 0; + [self src_withSampleOfSlot:slot key:key body:^(const Sample &s) { + secs = s.sampleRate > 0 ? (double)s.data.size() / s.sampleRate : 0; + }]; + return secs; +} + @end diff --git a/ios/app/Host/SizzleSession+Viz.h b/ios/app/Host/SizzleSession+Viz.h index 1763365..9d44380 100644 --- a/ios/app/Host/SizzleSession+Viz.h +++ b/ios/app/Host/SizzleSession+Viz.h @@ -7,6 +7,15 @@ NS_ASSUME_NONNULL_BEGIN /// API for the device editors' Viz views beyond SizzleSession.h. @interface SizzleSession (Viz) + +/// Toolbox [slot]'s live effect scope (AudioEngine.effectScope): copies up to +/// [capacity] samples, oldest to newest, into [out] and returns the count, or -1 +/// while the slot isn't a scope effect on a mixer channel (nothing to draw). +/// Lock-free (doesn't take the song lock), so it can be polled at display rate. +- (NSInteger)copyEffectScopeOfSlot:(NSInteger)slot into:(float *)out capacity:(NSInteger)capacity; +/// Its read head within the scope window, 0 (oldest) to 1 (newest), or -1. +- (float)effectPlayheadOfSlot:(NSInteger)slot; + @end NS_ASSUME_NONNULL_END diff --git a/ios/app/Host/SizzleSession+Viz.mm b/ios/app/Host/SizzleSession+Viz.mm index 23962c0..cdd2c2c 100644 --- a/ios/app/Host/SizzleSession+Viz.mm +++ b/ios/app/Host/SizzleSession+Viz.mm @@ -3,8 +3,35 @@ #import "SizzleSession+Viz.h" #import "SizzleSession+Internal.h" +#import using namespace sizzle; +static char kVizEngineKey; + @implementation SizzleSession (Viz) + +/// The engine, without the song lock: polling under it at display rate would make +/// the audio thread (which only try-locks) drop a block now and then. The engine is +/// created once with the session and lives as long as it, so its address is fetched +/// once under the lock and kept; Engine::effectScope / effectPlayhead are lock-free. +- (const engine::Engine *)vizEngine { + NSValue *v = objc_getAssociatedObject(self, &kVizEngineKey); + if (!v) { + __block const engine::Engine *e = nullptr; + [self read:^(const model::Project &, const engine::Engine &eng) { e = ŋ }]; + v = [NSValue valueWithPointer:e]; + objc_setAssociatedObject(self, &kVizEngineKey, v, OBJC_ASSOCIATION_RETAIN_NONATOMIC); + } + return (const engine::Engine *)v.pointerValue; +} + +- (NSInteger)copyEffectScopeOfSlot:(NSInteger)slot into:(float *)out capacity:(NSInteger)capacity { + return self.vizEngine->effectScope((int)slot, out, (int)capacity); +} + +- (float)effectPlayheadOfSlot:(NSInteger)slot { + return self.vizEngine->effectPlayhead((int)slot); +} + @end diff --git a/ios/app/project.yml b/ios/app/project.yml index 4a11708..52fa05a 100644 --- a/ios/app/project.yml +++ b/ios/app/project.yml @@ -59,6 +59,7 @@ targets: - FX/SizzleDeviceAU.mm - FX/SizzleEffectAU.mm - FX/SizzleInstrumentAU.mm + - FX/SizzleDeviceAU+Sources.mm - FX/SizzleFXViewController.mm - FX/Editor - FX/DeviceLayouts.json diff --git a/ios/app/tests/ScreenBridging.h b/ios/app/tests/ScreenBridging.h index 6c640d3..e4b05c7 100644 --- a/ios/app/tests/ScreenBridging.h +++ b/ios/app/tests/ScreenBridging.h @@ -1,4 +1,5 @@ #import "SizzleDeviceAU.h" +#import "SizzleDeviceAU+Sources.h" #import "SizzleSession.h" #import "SnapshotComponents.h" #import "SizzleSession+Tracker.h" diff --git a/ios/app/tests/SnapshotBridging.h b/ios/app/tests/SnapshotBridging.h index 2e9ddae..49add6f 100644 --- a/ios/app/tests/SnapshotBridging.h +++ b/ios/app/tests/SnapshotBridging.h @@ -1,2 +1,3 @@ #import "SizzleDeviceAU.h" +#import "SizzleDeviceAU+Sources.h" #import "SnapshotComponents.h" diff --git a/ios/app/tests/au_test.mm b/ios/app/tests/au_test.mm index 52ecfdd..e4335a8 100644 --- a/ios/app/tests/au_test.mm +++ b/ios/app/tests/au_test.mm @@ -15,7 +15,9 @@ // 4. zero-copy input: calling the render block directly with an upstream that // points the input buffers at its own memory instead of filling ours. Real // hosts do that out of process; AVAudioEngine in-process copies, which is why -// 0.1.0 passed here and was silent on the iPad. +// 0.1.0 passed here and was silent on the iPad; +// 6. effect scope (the Granular's VizEffect): -1 before audio, then once audio +// has passed through, the same scope and playhead as the core effect. #import #include @@ -24,6 +26,7 @@ #include #import "Components.gen.h" #import "SizzleDeviceAU.h" +#import "SizzleEffectAU.h" #import "SizzleInstrumentAU.h" #include "sizzle/Instrument.hpp" #include "sampler/SampleStore.hpp" @@ -100,7 +103,8 @@ static std::vector renderCore(const char *type, const Params &p, const st /// Render [in] through the AU's render block at 44.1 kHz in 512-frame blocks. The /// upstream hands over its own buffers (mData replaced, ours untouched); with /// [inPlace] the output buffers are null too, as hosts may pass them. -static void renderZeroCopy(AUAudioUnit *au, const std::vector &in, bool inPlace, std::vector &L, std::vector &R) { +static void renderZeroCopy(AUAudioUnit *au, const std::vector &in, bool inPlace, std::vector &L, std::vector &R, + bool deallocate = true) { au.maximumFramesToRender = 4096; NSError *err = nil; if (![au allocateRenderResourcesAndReturnError:&err]) { std::printf("allocate: %s\n", err.localizedDescription.UTF8String); return; } @@ -137,7 +141,7 @@ static void renderZeroCopy(AUAudioUnit *au, const std::vector &in, bool i L.insert(L.end(), l, l + n); R.insert(R.end(), r, r + n); } - [au deallocateRenderResources]; + if (deallocate) [au deallocateRenderResources]; } static double maxDiff(const std::vector &a, const std::vector &b) { @@ -310,6 +314,33 @@ int main(int argc, char **argv) { inPlace ? ", in-place output" : "", zl, zr); check(zl < 1e-6 && zr < 1e-6, msg, sc.name); } + + // 6. effect scope: none before audio; after it, the core effect's own + { + SizzleEffectAU *fau = (SizzleEffectAU *)instantiate(d).AUAudioUnit; + float scope[128], want[128]; + check([fau copyEffectScope:scope capacity:128] == -1 && fau.effectPlayhead == -1.f, + "scope: none before render resources", sc.name); + Params dp; dp.fill(*spec); + std::vector zin(in.begin(), in.begin() + 44032), zL, zR; + renderZeroCopy(fau, zin, false, zL, zR, false); + auto fx = Effect::create(sc.toolboxType, 44100); + fx->update(dp, 120.f); + for (float x : zin) fx->process(x); + NSInteger n = [fau copyEffectScope:scope capacity:128]; + int wn = fx->copyScope(want, 128); + if (fx->hasScope()) { + bool same = n == wn && n > 0 && !memcmp(scope, want, (size_t)n * 4) && fau.effectPlayhead == fx->playhead(); + float peak = 0; for (NSInteger i = 0; i < n; ++i) peak = std::max(peak, std::fabs(scope[i])); + snprintf(msg, sizeof msg, "scope after audio: %ld samples (peak %.2f), playhead %.3f, == core", + (long)n, peak, fau.effectPlayhead); + check(same && peak > 0.f && fau.effectPlayhead >= 0.f && fau.effectPlayhead <= 1.f, msg, sc.name); + } else { + check(n == -1 && fau.effectPlayhead == -1.f, "scope: none (not a scope effect)", sc.name); + } + [fau deallocateRenderResources]; + check([fau copyEffectScope:scope capacity:128] == -1, "scope: none after deallocation", sc.name); + } } std::printf("\n%s (%d failures)\n", failures ? "FAILED" : "all passed", failures); } diff --git a/ios/core/include/sizzle/Effect.hpp b/ios/core/include/sizzle/Effect.hpp index 3b9d789..7c50fcc 100644 --- a/ios/core/include/sizzle/Effect.hpp +++ b/ios/core/include/sizzle/Effect.hpp @@ -19,6 +19,19 @@ public: virtual void update(const Params &p, float tempoBpm) = 0; virtual float process(float x) = 0; + // ---- visualisation (Kotlin's VizEffect), optional + // The audio thread publishes a small snapshot while it runs process(); the UI + // reads it at frame rate from another thread, without locks (relaxed atomics: a + // value one frame stale is harmless). Publishing must never change the audio. + + /** True if this effect publishes a scope and playhead (a VizEffect). */ + virtual bool hasScope() const { return false; } + /** Copy up to [capacity] of the latest scope samples, oldest to newest, into + * [out]; returns the count written, or -1 if the effect has no scope. */ + virtual int copyScope(float *out, int capacity) const { (void)out; (void)capacity; return -1; } + /** The read/play head within the scope window, 0 (oldest) to 1 (newest), or -1. */ + virtual float playhead() const { return -1.f; } + /** The effect for ToolboxType name [type] ("DELAY", "FILTER", …), or nullptr * for types without an audio processor (the MIDI effects) or not ported yet. */ static std::unique_ptr create(const char *type, int sampleRate); diff --git a/ios/core/include/sizzle/Engine.hpp b/ios/core/include/sizzle/Engine.hpp index 20d3286..1e6188c 100644 --- a/ios/core/include/sizzle/Engine.hpp +++ b/ios/core/include/sizzle/Engine.hpp @@ -115,7 +115,11 @@ public: // ---- mixer meters (any thread, display only) float channelMeter(int ch) const; bool channelClipped(int ch) const; - /** Effect visualisation isn't ported: always -1 (nothing to draw). */ + /** Effect visualisation (AudioEngine.effectScope / effectPlayhead), any thread: + * toolbox [slotIndex]'s live scope (oldest → newest, up to [capacity] samples) + * and read head (0..1) from the first channel chain that runs it, or -1 when it + * isn't a scope effect placed on a mixer channel (nothing to draw). Lock-free; + * chains swapped out meanwhile are kept alive until the read is done. */ int effectScope(int slotIndex, float *out, int capacity) const; float effectPlayhead(int slotIndex) const; diff --git a/ios/core/src/engine/Engine.cpp b/ios/core/src/engine/Engine.cpp index 76a32d2..2509407 100644 --- a/ios/core/src/engine/Engine.cpp +++ b/ios/core/src/engine/Engine.cpp @@ -89,6 +89,7 @@ int64_t ver(const ToolboxSlot &s) { return (int64_t)(int32_t)s.version; } struct FxUnit { ToolboxSlot *slot; std::unique_ptr effect; + int slotIndex = -1; // slot->index, kept so viz readers never touch the project int64_t lastVersion = -1; float lastTempo = NaNf; }; @@ -219,6 +220,10 @@ public: std::vector retiredLists; void collectRetired(); + // ---- effect visualisation (UI thread): readers in flight hold retired chains + mutable std::atomic vizReaders{0}; + const Effect *vizFor(const Chains *chains, int slotIndex) const; + // ---- AudioEngine SynthVoice &allocSynthVoice(int bus); SampleVoice &allocSampleVoice(int bus); @@ -348,8 +353,12 @@ Engine::Impl::~Impl() { void Engine::Impl::collectRetired() { const uint64_t done = blocksDone.load(); - for (size_t i = 0; i < retiredChains.size();) - if (done > retiredChains[i].at) retiredChains.erase(retiredChains.begin() + (long)i); else ++i; + // A viz reader may still be walking a retired chain; keep them all until it's out. + // (seq_cst: a reader that arrives after this check loads the current chains.) + if (vizReaders.load() == 0) { + for (size_t i = 0; i < retiredChains.size();) + if (done > retiredChains[i].at) retiredChains.erase(retiredChains.begin() + (long)i); else ++i; + } for (size_t i = 0; i < retiredLists.size();) if (done > retiredLists[i].at) retiredLists.erase(retiredLists.begin() + (long)i); else ++i; } @@ -442,7 +451,7 @@ void Engine::Impl::rebuildFxChains() { ToolboxSlot *slot = slotAt(*proj, slotIndex); if (!slot || slot->type.empty()) continue; if (auto fx = Effect::create(slot->type.c_str(), sampleRate)) { - FxUnit u{slot, std::move(fx)}; + FxUnit u{slot, std::move(fx), slotIndex}; next->ch[ch].push_back(std::move(u)); } } @@ -1237,8 +1246,31 @@ float Engine::channelMeter(int ch) const { bool Engine::channelClipped(int ch) const { return ch >= 0 && ch < TRACK_COUNT && impl->chClipHold[ch].load(std::memory_order_relaxed) > 0; } -int Engine::effectScope(int, float *, int) const { return -1; } -float Engine::effectPlayhead(int) const { return -1.f; } +/** AudioEngine.vizFor: the first effect of toolbox [slotIndex] in any channel's chain + * that publishes a scope, or nullptr. */ +const Effect *Engine::Impl::vizFor(const Chains *chains, int slotIndex) const { + if (!chains) return nullptr; + for (const auto &ch : chains->ch) + for (const FxUnit &u : ch) + if (u.slotIndex == slotIndex && u.effect->hasScope()) return u.effect.get(); + return nullptr; +} + +int Engine::effectScope(int slotIndex, float *out, int capacity) const { + impl->vizReaders.fetch_add(1); + const Effect *e = impl->vizFor(impl->channelChains.load(), slotIndex); + int n = e ? e->copyScope(out, capacity) : -1; + impl->vizReaders.fetch_sub(1); + return n; +} + +float Engine::effectPlayhead(int slotIndex) const { + impl->vizReaders.fetch_add(1); + const Effect *e = impl->vizFor(impl->channelChains.load(), slotIndex); + float p = e ? e->playhead() : -1.f; + impl->vizReaders.fetch_sub(1); + return p; +} void Engine::setMidiOutEnabled(bool on) { impl->midiOutEnabled.store(on); } bool Engine::midiOutEnabled() const { return impl->midiOutEnabled.load(); } diff --git a/ios/core/src/fx/GranularGlitch.cpp b/ios/core/src/fx/GranularGlitch.cpp index 473406d..0d940e9 100644 --- a/ios/core/src/fx/GranularGlitch.cpp +++ b/ios/core/src/fx/GranularGlitch.cpp @@ -1,10 +1,13 @@ // SPDX-FileCopyrightText: 2026 Reactorcoremeltdown // SPDX-License-Identifier: GPL-3.0-or-later -// Port of GranularGlitch (Effects.kt), audio path only: a rolling 1 s buffer whose -// read head randomly jumps back to replay short (sometimes octave-shifted) grains, -// dry in between. The VizEffect scope/playhead is not ported (output-independent). +// Port of GranularGlitch (Effects.kt): a rolling 1 s buffer whose read head randomly +// jumps back to replay short (sometimes octave-shifted) grains, dry in between. Also +// its VizEffect side: a decimated scope of the incoming signal and the read head's +// place in that window, written here with relaxed atomics (plain stores on arm64 and +// x86) and read by the editor from the UI thread. It never feeds back into the audio. +#include #include #include #include "sizzle/Effect.hpp" @@ -18,6 +21,8 @@ constexpr float MIN_JUMP_S = 0.03f; constexpr float MAX_JUMP_S = 0.5f; constexpr float GRAIN_MIN_S = 0.02f; constexpr float GRAIN_MAX_S = 0.15f; +constexpr int SCOPE_N = 96; // scope points drawn +constexpr int SCOPE_DECIM = 96; // input samples per point (~192 ms window at 48 kHz) class GranularGlitch final : public Effect { int sampleRate; @@ -30,6 +35,12 @@ class GranularGlitch final : public Effect { float intensity = 0.f; uint32_t rng = 0x2F6E1DB7u; + // Visualisation: a ring of decimated INPUT samples plus the normalised read head. + std::atomic scope[SCOPE_N]; + std::atomic scopeWrite{0}; + int decCount = 0; + std::atomic playheadNorm{1.f}; + float nextUnit() { uint32_t s = rng; s ^= s << 13; s ^= s >> 17; s ^= s << 5; rng = s; return (float)s * 2.3283064e-10f; // 0 … 1 @@ -52,7 +63,9 @@ class GranularGlitch final : public Effect { } public: - explicit GranularGlitch(int rate) : sampleRate(rate), buf((size_t)rate, 0.f), size(rate) {} + explicit GranularGlitch(int rate) : sampleRate(rate), buf((size_t)rate, 0.f), size(rate) { + for (auto &v : scope) v.store(0.f, std::memory_order_relaxed); + } void update(const Params &p, float) override { intensity = kt::coerceIn(p.f("intensity", 0.3f), 0.f, 1.f); @@ -80,8 +93,33 @@ public: readPos = rp; grainLeft--; } + + // Scope: decimate the incoming signal into the ring. + if (++decCount >= SCOPE_DECIM) { + decCount = 0; + int sw = scopeWrite.load(std::memory_order_relaxed); + scope[sw].store(x, std::memory_order_relaxed); + sw++; if (sw >= SCOPE_N) sw = 0; + scopeWrite.store(sw, std::memory_order_relaxed); + } + // Playhead: where the read head sits within the displayed window (0 oldest … 1 now). + double behind = wp - readPos; if (behind < 0) behind += size; + playheadNorm.store(kt::coerceIn(1.f - (float)behind / (float)(SCOPE_N * SCOPE_DECIM), 0.f, 1.f), + std::memory_order_relaxed); return out; } + + bool hasScope() const override { return true; } + + int copyScope(float *out, int capacity) const override { + int n = capacity < SCOPE_N ? capacity : SCOPE_N; + if (n < 0) n = 0; + int start = scopeWrite.load(std::memory_order_relaxed); // oldest sample in the ring + for (int k = 0; k < n; ++k) out[k] = scope[(start + k) % SCOPE_N].load(std::memory_order_relaxed); + return n; + } + + float playhead() const override { return playheadNorm.load(std::memory_order_relaxed); } }; } // namespace diff --git a/versions.properties b/versions.properties index e5a38b1..05c64da 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.4.1 -ios.versionCode = 9 +ios.versionName = 0.5.0 +ios.versionCode = 10 macos.versionName = - linux.versionName = - bsd.versionName = -