Files
sizzletracker-android/ios/app/FX/Editor/Bespoke/GrainCloudBespoke.swift
T
ReactorcoremeltdownandClaude Opus 5.5 64e21e0bcc iOS 0.6.0: milestone 5 (recording, MIDI, input bindings, themes, bundles, backups)
- Master recording (MasterSink ring + writer thread) and the sample recorder
- CoreMIDI in/out: sound module, clock send/follow, virtual "Sizzle" ports;
  platform-free parser/module/clock in core (midi_test)
- Hardware keyboard and gamepads via GameController; rebindable keyboard,
  gamepad and MIDI CC actions; per-parameter MIDI learn
- Colour themes (.szt), project bundles (.szgz), backup & restore;
  ZIP in core with zlib (zip_test against jar and unzip)
- Persistent app settings; audio pauses in the background unless sound module

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 14:26:01 +01:00

157 lines
7.7 KiB
Swift

// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
import SwiftUI
import UniformTypeIdentifiers
/// A sample's length beside its peaks (the source strip's caption). Both backends
/// adopt it; a data source without it just shows no length.
@MainActor
protocol SampleLengthSource: AnyObject {
/// Seconds of the sample the setting [key] names, or nil.
func sampleSeconds(key: String) -> 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 (the app only)
/// makes a microphone take the source.
@MainActor
enum GrainCloudBespoke {
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
@Environment(\.deviceRecorder) private var recorder
@State private var importError: String?
/// Bumped while a built-in source is still being rendered, to look again.
@State private var retry = 0
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 } }
if let rec = recorder {
Text(rec.isRecording ? "■ STOP REC" : "● RECORD").font(Theme.mono(12))
.foregroundColor(rec.isRecording ? Theme.background : Theme.accent)
.padding(.horizontal, 10).padding(.vertical, 6)
.background(rec.isRecording ? Theme.accent : Theme.surface)
.overlay(Rectangle().stroke(Theme.accent.opacity(0.6), lineWidth: 1))
.contentShape(Rectangle())
.onTapGesture(perform: rec.toggle)
}
Spacer(minLength: 0)
}
Text(caption).font(Theme.mono(10)).foregroundColor(Theme.dim)
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."
}
}
}