iOS 0.2.0: instruments as AUv3, in-app host with keyboard, MIDI in and benchmark
Shared SizzleDeviceAU base for effects and instruments; sizzle::Instrument voice pools; Android's factory presets generated into the specs header; the app hosts every device in-process (no dependence on the system plugin registry). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
a5b2f4c873
commit
7f231c8f79
@@ -1 +1,3 @@
|
||||
#import "ObjC/SPKTry.h"
|
||||
#import "SizzleHost.h"
|
||||
#import "SizzleFXViewController.h"
|
||||
|
||||
@@ -2,36 +2,111 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
import SwiftUI
|
||||
import UniformTypeIdentifiers
|
||||
|
||||
/// The container app: what Sizzle installs as plugins, and an on-device check
|
||||
/// that each one loads and processes sound. The plugins themselves are used from
|
||||
/// a host (AUM, GarageBand, Loopy, …).
|
||||
/// 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 {
|
||||
@StateObject private var model = HostModel()
|
||||
@StateObject private var check = PluginCheck()
|
||||
@State private var importing = false
|
||||
@State private var pad = 0
|
||||
@State private var showReport = false
|
||||
|
||||
var body: some View {
|
||||
VStack(alignment: .leading, spacing: 12) {
|
||||
VStack(alignment: .leading, spacing: 10) {
|
||||
header
|
||||
controls
|
||||
editor
|
||||
HStack {
|
||||
Button("−") { model.octave = max(0, model.octave - 1) }.buttonStyle(.bordered)
|
||||
Text("C\(model.octave)").font(.system(.body, design: .monospaced)).frame(width: 40)
|
||||
Button("+") { model.octave = min(7, model.octave + 1) }.buttonStyle(.bordered)
|
||||
Spacer()
|
||||
Text(model.host.midiSources.isEmpty ? "No MIDI input" : "MIDI: " + model.host.midiSources.joined(separator: ", "))
|
||||
.font(.system(.caption, design: .monospaced)).foregroundColor(.gray).lineLimit(1)
|
||||
}
|
||||
KeyboardView(octave: model.octave,
|
||||
noteOn: { model.host.note(on: Int32($0), velocity: 100) },
|
||||
noteOff: { model.host.noteOff(Int32($0)) })
|
||||
.frame(height: 150)
|
||||
}
|
||||
.padding()
|
||||
.preferredColorScheme(.dark)
|
||||
.fileImporter(isPresented: $importing, allowedContentTypes: [.audio, .data]) { result in
|
||||
if case .success(let url) = result { model.loadSample(url, pad: pad) }
|
||||
}
|
||||
.sheet(isPresented: $showReport) { reportSheet }
|
||||
.alert(model.message ?? "", isPresented: Binding(get: { model.message != nil }, set: { if !$0 { model.message = nil } })) {
|
||||
Button("OK") { model.message = nil }
|
||||
}
|
||||
}
|
||||
|
||||
private var header: some View {
|
||||
HStack(alignment: .firstTextBaseline) {
|
||||
Text("Sizzle").font(.system(.largeTitle, design: .monospaced)).foregroundColor(.orange)
|
||||
Text("AUv3 plugins for AUM, GarageBand, Loopy and other hosts.\nLook for \"Tired Sysadmin: Sizzle …\".")
|
||||
.font(.system(.footnote, design: .monospaced)).foregroundColor(.gray)
|
||||
Text(versionLine).font(.system(.caption, design: .monospaced)).foregroundColor(.gray)
|
||||
Button("Check all plugins") { Task { await check.run() } }
|
||||
.buttonStyle(.bordered).disabled(check.running)
|
||||
Spacer()
|
||||
Button("Benchmark") { model.benchmark(); showReport = true }.disabled(model.busy)
|
||||
Button("Check plugins") { showReport = true; Task { await check.run() } }
|
||||
}
|
||||
}
|
||||
|
||||
private var controls: some View {
|
||||
HStack {
|
||||
Menu {
|
||||
ForEach(model.instruments, id: \.subtype) { d in Button(d.name) { model.select(d) } }
|
||||
} label: { Label(model.instrument?.name ?? "Instrument", systemImage: "pianokeys") }
|
||||
Image(systemName: "arrow.right").foregroundColor(.gray)
|
||||
Menu {
|
||||
Button("No effect") { model.selectEffect(nil) }
|
||||
ForEach(model.effects, id: \.subtype) { d in Button(d.name) { model.selectEffect(d) } }
|
||||
} label: { Label(model.effect?.name ?? "No effect", systemImage: "slider.horizontal.3") }
|
||||
Spacer()
|
||||
if model.effect != nil {
|
||||
Picker("Edit", selection: $model.editingEffect) {
|
||||
Text("Instrument").tag(false)
|
||||
Text("Effect").tag(true)
|
||||
}.pickerStyle(.segmented).frame(width: 220)
|
||||
}
|
||||
if model.canLoadSample {
|
||||
if model.instrument?.toolboxType == "SAMPLER" {
|
||||
Stepper("Pad \(pad + 1)", value: $pad, in: 0...15).frame(width: 150)
|
||||
}
|
||||
Button("Load sample…") { importing = true }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ViewBuilder private var editor: some View {
|
||||
if let unit = model.editedUnit {
|
||||
DeviceEditorView(unit: unit)
|
||||
.id(ObjectIdentifier(unit))
|
||||
.frame(maxHeight: .infinity)
|
||||
} else {
|
||||
Spacer()
|
||||
}
|
||||
}
|
||||
|
||||
private var reportSheet: some View {
|
||||
VStack(alignment: .leading, spacing: 8) {
|
||||
Text("Benchmark and plugin check").font(.headline)
|
||||
ScrollView {
|
||||
Text(check.lines.joined(separator: "\n"))
|
||||
Text((model.report + [""] + check.lines).joined(separator: "\n"))
|
||||
.font(.system(.footnote, design: .monospaced))
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
.textSelection(.enabled)
|
||||
}
|
||||
if model.busy { ProgressView() }
|
||||
}
|
||||
.padding()
|
||||
.preferredColorScheme(.dark)
|
||||
.onAppear { check.listInstalled() }
|
||||
}
|
||||
|
||||
private var versionLine: String {
|
||||
let v = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "?"
|
||||
let b = Bundle.main.infoDictionary?["CFBundleVersion"] as? String ?? "?"
|
||||
return "version \(v) (\(b)) · iOS \(ProcessInfo.processInfo.operatingSystemVersionString)"
|
||||
return "\(v) (\(b))"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
import SwiftUI
|
||||
|
||||
/// The plugins' own editor (SizzleFXViewController) for a device the app hosts.
|
||||
struct DeviceEditorView: UIViewControllerRepresentable {
|
||||
let unit: SizzleDeviceAU
|
||||
|
||||
func makeUIViewController(context: Context) -> SizzleFXViewController {
|
||||
let vc = SizzleFXViewController()
|
||||
vc.attachAudioUnit(unit)
|
||||
return vc
|
||||
}
|
||||
|
||||
func updateUIViewController(_ vc: SizzleFXViewController, context: Context) {}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
import SwiftUI
|
||||
|
||||
/// The app's state around SizzleHost: which devices play, which editor shows,
|
||||
/// and the results of the benchmark / plugin check.
|
||||
@MainActor
|
||||
final class HostModel: ObservableObject {
|
||||
let host = SizzleHost()
|
||||
let devices = SizzleHost.devices
|
||||
var instruments: [SizzleHostDevice] { devices.filter { $0.isInstrument } }
|
||||
var effects: [SizzleHostDevice] { devices.filter { !$0.isInstrument } }
|
||||
|
||||
@Published var instrument: SizzleHostDevice?
|
||||
@Published var effect: SizzleHostDevice?
|
||||
/// Which device's editor is shown: false = the instrument, true = the effect.
|
||||
@Published var editingEffect = false
|
||||
@Published var octave = 4
|
||||
@Published var report: [String] = []
|
||||
@Published var busy = false
|
||||
@Published var message: String?
|
||||
|
||||
init() {
|
||||
if let first = instruments.first { select(first) }
|
||||
}
|
||||
|
||||
func select(_ device: SizzleHostDevice) {
|
||||
host.selectInstrument(device) { [weak self] error in
|
||||
guard let self = self else { return }
|
||||
if let error = error { self.message = error.localizedDescription; return }
|
||||
self.instrument = device
|
||||
self.editingEffect = false
|
||||
}
|
||||
}
|
||||
|
||||
func selectEffect(_ device: SizzleHostDevice?) {
|
||||
host.selectEffect(device) { [weak self] error in
|
||||
guard let self = self else { return }
|
||||
if let error = error { self.message = error.localizedDescription; return }
|
||||
self.effect = device
|
||||
self.editingEffect = device != nil
|
||||
}
|
||||
}
|
||||
|
||||
var editedUnit: SizzleDeviceAU? { editingEffect ? host.effect : host.instrument }
|
||||
|
||||
var canLoadSample: Bool {
|
||||
let t = instrument?.toolboxType
|
||||
return t == "SAMPLER" || t == "SOUNDFONT"
|
||||
}
|
||||
|
||||
func loadSample(_ url: URL, pad: Int) {
|
||||
do { try host.loadSample(from: url, pad: Int32(pad)) }
|
||||
catch { message = error.localizedDescription }
|
||||
}
|
||||
|
||||
func benchmark() {
|
||||
busy = true
|
||||
report = []
|
||||
host.benchmark({ [weak self] line in self?.report.append(line) },
|
||||
done: { [weak self] in self?.busy = false })
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>CFBundleDevelopmentRegion</key>
|
||||
<string>$(DEVELOPMENT_LANGUAGE)</string>
|
||||
<key>CFBundleExecutable</key>
|
||||
<string>$(EXECUTABLE_NAME)</string>
|
||||
<key>CFBundleIdentifier</key>
|
||||
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
|
||||
<key>CFBundleInfoDictionaryVersion</key>
|
||||
<string>6.0</string>
|
||||
<key>CFBundleName</key>
|
||||
<string>$(PRODUCT_NAME)</string>
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>APPL</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>1.0</string>
|
||||
<key>CFBundleVersion</key>
|
||||
<string>1</string>
|
||||
<key>UIBackgroundModes</key>
|
||||
<array>
|
||||
<string>audio</string>
|
||||
</array>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -0,0 +1,59 @@
|
||||
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
import SwiftUI
|
||||
|
||||
/// Two octaves of piano keys from C of [octave] (MIDI 60 = C4). Each key tracks its
|
||||
/// own touch, so chords work; a key sends note-on on touch and note-off on release.
|
||||
struct KeyboardView: View {
|
||||
let octave: Int
|
||||
let noteOn: (Int) -> Void
|
||||
let noteOff: (Int) -> Void
|
||||
|
||||
private let whiteSteps = [0, 2, 4, 5, 7, 9, 11]
|
||||
private let blackSteps: [(step: Int, afterWhite: Int)] = [(1, 0), (3, 1), (6, 3), (8, 4), (10, 5)]
|
||||
|
||||
var body: some View {
|
||||
GeometryReader { geo in
|
||||
let whites = 14
|
||||
let w = geo.size.width / CGFloat(whites)
|
||||
let base = (octave + 1) * 12
|
||||
ZStack(alignment: .topLeading) {
|
||||
HStack(spacing: 1) {
|
||||
ForEach(0..<whites, id: \.self) { i in
|
||||
Key(note: base + (i / 7) * 12 + whiteSteps[i % 7], black: false, noteOn: noteOn, noteOff: noteOff)
|
||||
.frame(width: w - 1, height: geo.size.height)
|
||||
}
|
||||
}
|
||||
ForEach(0..<10, id: \.self) { i in
|
||||
let o = i / 5, b = blackSteps[i % 5]
|
||||
Key(note: base + o * 12 + b.step, black: true, noteOn: noteOn, noteOff: noteOff)
|
||||
.frame(width: w * 0.6, height: geo.size.height * 0.6)
|
||||
.offset(x: CGFloat(o * 7 + b.afterWhite + 1) * w - w * 0.3)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private struct Key: View {
|
||||
let note: Int
|
||||
let black: Bool
|
||||
let noteOn: (Int) -> Void
|
||||
let noteOff: (Int) -> Void
|
||||
@State private var down = false
|
||||
|
||||
var body: some View {
|
||||
Rectangle()
|
||||
.fill(down ? Color.orange : (black ? Color(white: 0.12) : Color(white: 0.92)))
|
||||
.overlay(alignment: .bottom) {
|
||||
if !black && note % 12 == 0 {
|
||||
Text("C\(note / 12 - 1)").font(.system(size: 10, design: .monospaced))
|
||||
.foregroundColor(.gray).padding(.bottom, 4)
|
||||
}
|
||||
}
|
||||
.gesture(DragGesture(minimumDistance: 0)
|
||||
.onChanged { _ in if !down { down = true; noteOn(note) } }
|
||||
.onEnded { _ in down = false; noteOff(note) })
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -18,19 +18,19 @@ final class PluginCheck: ObservableObject {
|
||||
componentManufacturer: Self.manufacturer,
|
||||
componentFlags: 0, componentFlagsMask: 0)
|
||||
return AVAudioUnitComponentManager.shared().components(matching: any)
|
||||
.filter { $0.audioComponentDescription.componentType == kAudioUnitType_Effect }
|
||||
.filter { [kAudioUnitType_Effect, kAudioUnitType_MusicDevice].contains($0.audioComponentDescription.componentType) }
|
||||
}
|
||||
|
||||
func listInstalled() {
|
||||
let comps = installed()
|
||||
lines = ["Registered effects: \(comps.count)"] + comps.map { " \($0.name)" }
|
||||
lines = ["Registered plugins (extension): \(comps.count)"] + comps.map { " \($0.name)" }
|
||||
}
|
||||
|
||||
func run() async {
|
||||
running = true
|
||||
defer { running = false }
|
||||
let comps = installed()
|
||||
lines = ["Checking \(comps.count) effects…"]
|
||||
lines = ["Plugin extension (as AUM loads it): \(comps.count) registered"]
|
||||
var ok = 0
|
||||
for c in comps {
|
||||
let result = await check(c)
|
||||
@@ -86,13 +86,20 @@ final class PluginCheck: ObservableObject {
|
||||
let ex = SPKTry {
|
||||
do {
|
||||
try engine.enableManualRenderingMode(.offline, format: format, maximumFrameCount: 4096)
|
||||
engine.attach(player)
|
||||
engine.attach(unit)
|
||||
engine.connect(player, to: unit, format: format)
|
||||
engine.connect(unit, to: engine.mainMixerNode, format: format)
|
||||
try engine.start()
|
||||
player.scheduleBuffer(self.testBuffer(format: format), completionHandler: nil)
|
||||
player.play()
|
||||
if let inst = unit as? AVAudioUnitMIDIInstrument {
|
||||
engine.connect(unit, to: engine.mainMixerNode, format: format)
|
||||
try engine.start()
|
||||
inst.startNote(60, withVelocity: 100, onChannel: 0)
|
||||
inst.startNote(64, withVelocity: 100, onChannel: 0)
|
||||
} else {
|
||||
engine.attach(player)
|
||||
engine.connect(player, to: unit, format: format)
|
||||
engine.connect(unit, to: engine.mainMixerNode, format: format)
|
||||
try engine.start()
|
||||
player.scheduleBuffer(self.testBuffer(format: format), completionHandler: nil)
|
||||
player.play()
|
||||
}
|
||||
} catch { thrown = error }
|
||||
}
|
||||
if let ex = ex { return "FAIL exception \(ex)" }
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
#import <AVFoundation/AVFoundation.h>
|
||||
#import "SizzleDeviceAU.h"
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
/// One Sizzle device the app can host (from components.txt).
|
||||
NS_SWIFT_SENDABLE
|
||||
@interface SizzleHostDevice : NSObject
|
||||
@property (nonatomic, readonly) NSString *name;
|
||||
@property (nonatomic, readonly) NSString *toolboxType;
|
||||
@property (nonatomic, readonly) OSType subtype;
|
||||
@property (nonatomic, readonly) BOOL isInstrument;
|
||||
@end
|
||||
|
||||
/**
|
||||
* The app's own host: Sizzle's devices registered in this process (manufacturer
|
||||
* 'Tsyl', so they never collide with the extension's 'Tsys' copies and don't depend
|
||||
* on the system plugin registry), played through AVAudioEngine:
|
||||
* instrument → optional effect → output. Notes come from the on-screen keyboard
|
||||
* and every connected MIDI source. Main thread only.
|
||||
*/
|
||||
NS_SWIFT_UI_ACTOR
|
||||
@interface SizzleHost : NSObject
|
||||
|
||||
@property (class, nonatomic, readonly) NSArray<SizzleHostDevice *> *devices;
|
||||
|
||||
@property (nonatomic, readonly, nullable) SizzleDeviceAU *instrument;
|
||||
@property (nonatomic, readonly, nullable) SizzleDeviceAU *effect;
|
||||
@property (nonatomic, readonly) NSArray<NSString *> *midiSources;
|
||||
|
||||
/// Swap the instrument / the effect (nil = no effect). Completion on the main thread.
|
||||
- (void)selectInstrument:(SizzleHostDevice *)device completion:(NS_SWIFT_UI_ACTOR void (^)(NSError *_Nullable))completion;
|
||||
- (void)selectEffect:(nullable SizzleHostDevice *)device completion:(NS_SWIFT_UI_ACTOR void (^)(NSError *_Nullable))completion;
|
||||
|
||||
- (void)noteOn:(int)note velocity:(int)velocity;
|
||||
- (void)noteOff:(int)note;
|
||||
- (void)allNotesOff;
|
||||
|
||||
/// Load a WAV (Sampler: into pad [pad]) or SF2/XI (SF2/XI loader) into the current
|
||||
/// instrument. Returns NO with a message in [error] if the file can't be used.
|
||||
- (BOOL)loadSampleFromURL:(NSURL *)url pad:(int)pad error:(NSError **)error;
|
||||
|
||||
/// Render every device offline for 10 s of audio (instruments with 8 notes held,
|
||||
/// effects on noise) and report each one's cost as a share of one CPU core.
|
||||
/// Lines arrive on the main thread; runs on a background thread.
|
||||
- (void)benchmark:(NS_SWIFT_UI_ACTOR void (^)(NSString *line))line done:(NS_SWIFT_UI_ACTOR void (^)(void))done;
|
||||
|
||||
@end
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
@@ -0,0 +1,335 @@
|
||||
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
#import "SizzleHost.h"
|
||||
#import "Components.gen.h"
|
||||
#import "SizzleInstrumentAU.h"
|
||||
#import <CoreMIDI/CoreMIDI.h>
|
||||
#import <mach/mach_time.h>
|
||||
#import <sys/sysctl.h>
|
||||
|
||||
#include <cmath>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include "sampler/SampleStore.hpp"
|
||||
#include "sampler/SoundFontLoader.hpp"
|
||||
#include "echofield/GrainSources.hpp"
|
||||
#include "wavetable/WaveTables.hpp"
|
||||
|
||||
using namespace sizzle;
|
||||
|
||||
/// In-process registrations use their own manufacturer code, so they never clash
|
||||
/// with the extension's ('Tsys') when both are visible in this process.
|
||||
static const OSType kLocalManufacturer = 'Tsyl';
|
||||
|
||||
/// Samples for the Sampler, SF2/XI loader and Grain Cloud custom sources. Lives for
|
||||
/// the whole process, as the AUs require.
|
||||
static sampler::SampleStore &store() {
|
||||
static sampler::SampleStore *s = new sampler::SampleStore();
|
||||
return *s;
|
||||
}
|
||||
|
||||
static AudioComponentDescription descFor(const SizzleComponent &c) {
|
||||
return AudioComponentDescription{c.type, c.subtype, kLocalManufacturer, 0, 0};
|
||||
}
|
||||
|
||||
static void registerDevices() {
|
||||
static dispatch_once_t once;
|
||||
dispatch_once(&once, ^{
|
||||
for (int i = 0; i < kSizzleComponentCount; ++i) {
|
||||
const SizzleComponent &c = kSizzleComponents[i];
|
||||
[AUAudioUnit registerSubclass:[SizzleDeviceAU classForComponentType:c.type]
|
||||
asComponentDescription:descFor(c) name:@(c.name) version:1];
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
static NSError *hostError(NSString *msg) {
|
||||
return [NSError errorWithDomain:@"cc.tiredsysadmin.ios.sizzle" code:1 userInfo:@{NSLocalizedDescriptionKey: msg}];
|
||||
}
|
||||
|
||||
@implementation SizzleHostDevice {
|
||||
@public
|
||||
int _index;
|
||||
}
|
||||
- (NSString *)name { return @(kSizzleComponents[_index].name); }
|
||||
- (NSString *)toolboxType { return @(kSizzleComponents[_index].toolboxType); }
|
||||
- (OSType)subtype { return kSizzleComponents[_index].subtype; }
|
||||
- (BOOL)isInstrument { return kSizzleComponents[_index].type == kAudioUnitType_MusicDevice; }
|
||||
@end
|
||||
|
||||
@interface SizzleHost ()
|
||||
@property (atomic, copy, nullable) AUScheduleMIDIEventBlock midiBlock;
|
||||
@end
|
||||
|
||||
@implementation SizzleHost {
|
||||
AVAudioEngine *_engine;
|
||||
AVAudioUnit *_instNode;
|
||||
AVAudioUnit *_fxNode;
|
||||
MIDIClientRef _midiClient;
|
||||
MIDIPortRef _midiPort;
|
||||
NSArray<NSString *> *_midiSources;
|
||||
}
|
||||
|
||||
+ (NSArray<SizzleHostDevice *> *)devices {
|
||||
NSMutableArray *list = [NSMutableArray array];
|
||||
for (int i = 0; i < kSizzleComponentCount; ++i) {
|
||||
SizzleHostDevice *d = [SizzleHostDevice new];
|
||||
d->_index = i;
|
||||
[list addObject:d];
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
- (instancetype)init {
|
||||
self = [super init];
|
||||
if (!self) return nil;
|
||||
registerDevices();
|
||||
_engine = [AVAudioEngine new];
|
||||
_midiSources = @[];
|
||||
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
|
||||
[[AVAudioSession sharedInstance] setActive:YES error:nil];
|
||||
[self startMIDI];
|
||||
return self;
|
||||
}
|
||||
|
||||
- (SizzleDeviceAU *)instrument { return (SizzleDeviceAU *)_instNode.AUAudioUnit; }
|
||||
- (SizzleDeviceAU *)effect { return (SizzleDeviceAU *)_fxNode.AUAudioUnit; }
|
||||
- (NSArray<NSString *> *)midiSources { return _midiSources; }
|
||||
|
||||
#pragma mark - graph
|
||||
|
||||
- (void)instantiate:(SizzleHostDevice *)device completion:(void (^)(AVAudioUnit *_Nullable, NSError *_Nullable))completion {
|
||||
AudioComponentDescription d = descFor(kSizzleComponents[device->_index]);
|
||||
// Subclasses registered in this process always load in-process.
|
||||
[AVAudioUnit instantiateWithComponentDescription:d options:0
|
||||
completionHandler:^(AVAudioUnit *unit, NSError *error) {
|
||||
dispatch_async(dispatch_get_main_queue(), ^{ completion(unit, error); });
|
||||
}];
|
||||
}
|
||||
|
||||
- (void)rebuild {
|
||||
[_engine stop];
|
||||
for (AVAudioNode *n in [_engine.attachedNodes copy])
|
||||
if (n != _engine.mainMixerNode && n != _engine.outputNode && n != _engine.inputNode) [_engine detachNode:n];
|
||||
if (!_instNode) return;
|
||||
[_engine attachNode:_instNode];
|
||||
AVAudioNode *last = _instNode;
|
||||
if (_fxNode) {
|
||||
[_engine attachNode:_fxNode];
|
||||
[_engine connect:_instNode to:_fxNode format:nil];
|
||||
last = _fxNode;
|
||||
}
|
||||
[_engine connect:last to:_engine.mainMixerNode format:nil];
|
||||
NSError *err = nil;
|
||||
if (![_engine startAndReturnError:&err]) NSLog(@"engine start: %@", err);
|
||||
self.midiBlock = _instNode.AUAudioUnit.scheduleMIDIEventBlock;
|
||||
}
|
||||
|
||||
- (void)selectInstrument:(SizzleHostDevice *)device completion:(void (^)(NSError *))completion {
|
||||
[self instantiate:device completion:^(AVAudioUnit *unit, NSError *error) {
|
||||
if (!unit) { completion(error ?: hostError(@"Couldn't load the instrument.")); return; }
|
||||
((SizzleInstrumentAU *)unit.AUAudioUnit).sampleStore = &store();
|
||||
self.midiBlock = nil;
|
||||
self->_instNode = unit;
|
||||
[self rebuild];
|
||||
completion(nil);
|
||||
}];
|
||||
}
|
||||
|
||||
- (void)selectEffect:(SizzleHostDevice *)device completion:(void (^)(NSError *))completion {
|
||||
if (!device) { _fxNode = nil; [self rebuild]; completion(nil); return; }
|
||||
[self instantiate:device completion:^(AVAudioUnit *unit, NSError *error) {
|
||||
if (!unit) { completion(error ?: hostError(@"Couldn't load the effect.")); return; }
|
||||
self->_fxNode = unit;
|
||||
[self rebuild];
|
||||
completion(nil);
|
||||
}];
|
||||
}
|
||||
|
||||
#pragma mark - notes
|
||||
|
||||
- (void)send:(uint8_t)status d1:(uint8_t)d1 d2:(uint8_t)d2 {
|
||||
AUScheduleMIDIEventBlock b = self.midiBlock;
|
||||
if (!b) return;
|
||||
uint8_t bytes[3] = {status, d1, d2};
|
||||
b(AUEventSampleTimeImmediate, 0, 3, bytes);
|
||||
}
|
||||
|
||||
- (void)noteOn:(int)note velocity:(int)velocity { [self send:0x90 d1:(uint8_t)note d2:(uint8_t)velocity]; }
|
||||
- (void)noteOff:(int)note { [self send:0x80 d1:(uint8_t)note d2:0]; }
|
||||
- (void)allNotesOff { [self send:0xB0 d1:123 d2:0]; }
|
||||
|
||||
#pragma mark - MIDI input
|
||||
|
||||
- (void)startMIDI {
|
||||
__weak SizzleHost *weakSelf = self;
|
||||
MIDIClientCreateWithBlock(CFSTR("Sizzle"), &_midiClient, ^(const MIDINotification *n) {
|
||||
if (n->messageID == kMIDIMsgSetupChanged)
|
||||
dispatch_async(dispatch_get_main_queue(), ^{ [weakSelf connectSources]; });
|
||||
});
|
||||
MIDIInputPortCreateWithBlock(_midiClient, CFSTR("Sizzle in"), &_midiPort, ^(const MIDIPacketList *list, void *src) {
|
||||
AUScheduleMIDIEventBlock b = weakSelf.midiBlock;
|
||||
if (!b) return;
|
||||
const MIDIPacket *p = &list->packet[0];
|
||||
for (UInt32 i = 0; i < list->numPackets; ++i) {
|
||||
// Split the packet into channel messages (running status not used by
|
||||
// keyboards in practice; system messages are skipped).
|
||||
for (UInt16 j = 0; j < p->length;) {
|
||||
uint8_t st = p->data[j];
|
||||
if (st < 0x80 || st >= 0xF0) { ++j; continue; }
|
||||
int len = (st & 0xF0) == 0xC0 || (st & 0xF0) == 0xD0 ? 2 : 3;
|
||||
if (j + len > p->length) break;
|
||||
b(AUEventSampleTimeImmediate, 0, (NSInteger)len, &p->data[j]);
|
||||
j += (UInt16)len;
|
||||
}
|
||||
p = MIDIPacketNext(p);
|
||||
}
|
||||
});
|
||||
[self connectSources];
|
||||
}
|
||||
|
||||
- (void)connectSources {
|
||||
NSMutableArray *names = [NSMutableArray array];
|
||||
ItemCount n = MIDIGetNumberOfSources();
|
||||
for (ItemCount i = 0; i < n; ++i) {
|
||||
MIDIEndpointRef src = MIDIGetSource(i);
|
||||
MIDIPortConnectSource(_midiPort, src, nullptr);
|
||||
CFStringRef name = nullptr;
|
||||
MIDIObjectGetStringProperty(src, kMIDIPropertyDisplayName, &name);
|
||||
if (name) [names addObject:(__bridge_transfer NSString *)name];
|
||||
}
|
||||
_midiSources = names;
|
||||
}
|
||||
|
||||
#pragma mark - samples
|
||||
|
||||
- (BOOL)loadSampleFromURL:(NSURL *)url pad:(int)pad error:(NSError **)error {
|
||||
SizzleDeviceAU *au = self.instrument;
|
||||
NSString *type = au.toolboxType;
|
||||
if (![type isEqualToString:@"SAMPLER"] && ![type isEqualToString:@"SOUNDFONT"]) {
|
||||
if (error) *error = hostError(@"Pick the Sampler or the SF2/XI loader first.");
|
||||
return NO;
|
||||
}
|
||||
BOOL scoped = [url startAccessingSecurityScopedResource];
|
||||
NSData *data = [NSData dataWithContentsOfURL:url options:NSDataReadingMappedIfSafe error:error];
|
||||
if (scoped) [url stopAccessingSecurityScopedResource];
|
||||
if (!data) return NO;
|
||||
const uint8_t *bytes = (const uint8_t *)data.bytes;
|
||||
std::string id = std::string(url.lastPathComponent.UTF8String) + "#" + NSUUID.UUID.UUIDString.UTF8String;
|
||||
NSMutableDictionary *state = [au.fullState mutableCopy];
|
||||
NSMutableDictionary *values = [state[@"sizzleValues"] mutableCopy] ?: [NSMutableDictionary dictionary];
|
||||
if ([type isEqualToString:@"SOUNDFONT"]) {
|
||||
std::optional<sampler::SoundFontLoader::Loaded> loaded = sampler::SoundFontLoader::load(bytes, data.length);
|
||||
if (!loaded) {
|
||||
if (auto wav = sampler::SampleStore::decodeWav(bytes, data.length)) loaded = sampler::SoundFontLoader::Loaded{std::move(*wav), 60};
|
||||
}
|
||||
if (!loaded) { if (error) *error = hostError(@"Not an SF2, XI or WAV file Sizzle can read."); return NO; }
|
||||
int root = loaded->rootNote;
|
||||
store().put(id, std::move(loaded->sample));
|
||||
values[@"sfSample"] = @(id.c_str());
|
||||
values[@"sfRoot"] = [NSString stringWithFormat:@"%d.0", root];
|
||||
} else {
|
||||
std::optional<Sample> wav = sampler::SampleStore::decodeWav(bytes, data.length);
|
||||
if (!wav) { if (error) *error = hostError(@"Not a WAV file Sizzle can read."); return NO; }
|
||||
store().put(id, std::move(*wav));
|
||||
values[[NSString stringWithFormat:@"pad%d", pad]] = @(id.c_str());
|
||||
}
|
||||
state[@"sizzleValues"] = values;
|
||||
au.fullState = state;
|
||||
return YES;
|
||||
}
|
||||
|
||||
#pragma mark - benchmark
|
||||
|
||||
static NSString *machine() {
|
||||
size_t n = 0;
|
||||
sysctlbyname("hw.machine", nullptr, &n, nullptr, 0);
|
||||
std::string s(n, '\0');
|
||||
sysctlbyname("hw.machine", s.data(), &n, nullptr, 0);
|
||||
return @(s.c_str());
|
||||
}
|
||||
|
||||
/// Seconds to render [seconds] of audio through [au] in 256-frame blocks.
|
||||
static double timeRender(SizzleDeviceAU *au, BOOL instrument, double seconds) {
|
||||
const int sr = 44100, n = 256;
|
||||
au.maximumFramesToRender = 4096;
|
||||
NSError *err = nil;
|
||||
if (![au allocateRenderResourcesAndReturnError:&err]) return -1;
|
||||
if (instrument) {
|
||||
AUScheduleMIDIEventBlock midi = au.scheduleMIDIEventBlock;
|
||||
for (int k = 0; k < 8; ++k) { // a held 8-note chord, within the Sampler's pads
|
||||
uint8_t on[3] = {0x90, (uint8_t)(36 + k * 2), 100};
|
||||
midi(AUEventSampleTimeImmediate, 0, 3, on);
|
||||
}
|
||||
}
|
||||
std::vector<float> L(n), R(n), noise(n);
|
||||
uint32_t seed = 1;
|
||||
for (float &v : noise) { seed = seed * 1103515245u + 12345u; v = ((seed >> 8) & 0xFFFF) / 65535.f - 0.5f; }
|
||||
float *src = noise.data();
|
||||
AURenderPullInputBlock pull = ^AUAudioUnitStatus(AudioUnitRenderActionFlags *f, const AudioTimeStamp *t,
|
||||
AUAudioFrameCount frames, NSInteger bus, AudioBufferList *data) {
|
||||
for (UInt32 c = 0; c < data->mNumberBuffers; ++c) data->mBuffers[c].mData = src;
|
||||
return noErr;
|
||||
};
|
||||
AURenderBlock render = au.renderBlock;
|
||||
const int blocks = (int)(seconds * sr / n);
|
||||
uint64_t t0 = mach_absolute_time();
|
||||
for (int b = 0; b < blocks; ++b) {
|
||||
struct { AudioBufferList list; AudioBuffer extra; } out;
|
||||
out.list.mNumberBuffers = 2;
|
||||
out.list.mBuffers[0] = {1, (UInt32)(n * 4), L.data()};
|
||||
out.list.mBuffers[1] = {1, (UInt32)(n * 4), R.data()};
|
||||
AudioTimeStamp ts = {};
|
||||
ts.mSampleTime = (Float64)b * n;
|
||||
ts.mFlags = kAudioTimeStampSampleTimeValid;
|
||||
AudioUnitRenderActionFlags flags = 0;
|
||||
render(&flags, &ts, n, 0, &out.list, instrument ? (AURenderPullInputBlock)nil : pull);
|
||||
}
|
||||
uint64_t t1 = mach_absolute_time();
|
||||
[au deallocateRenderResources];
|
||||
mach_timebase_info_data_t tb;
|
||||
mach_timebase_info(&tb);
|
||||
return (double)(t1 - t0) * tb.numer / tb.denom / 1e9;
|
||||
}
|
||||
|
||||
- (void)benchmark:(void (^)(NSString *))line done:(void (^)(void))done {
|
||||
void (^say)(NSString *) = ^(NSString *s) { dispatch_async(dispatch_get_main_queue(), ^{ line(s); }); };
|
||||
dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{
|
||||
say([NSString stringWithFormat:@"%@ · %lu cores · 10 s of 44.1 kHz audio per device",
|
||||
machine(), (unsigned long)NSProcessInfo.processInfo.activeProcessorCount]);
|
||||
// Generated once on first use; time the devices, not the generation.
|
||||
wavetable::WaveTables::prewarmBlocking();
|
||||
echofield::GrainSources::prewarmBlocking();
|
||||
{ // a test sample for the Sampler pads 0..15 and the SF2/XI loader
|
||||
Sample s;
|
||||
s.sampleRate = 44100;
|
||||
for (int i = 0; i < 88200; ++i) s.data.push_back(0.5f * std::sin(i * 0.0313f) * std::exp(-i / 60000.f));
|
||||
s.loopStart = 4000; s.loopEnd = 40000;
|
||||
store().put("bench", std::move(s));
|
||||
}
|
||||
for (SizzleHostDevice *d in SizzleHost.devices) {
|
||||
NSError *err = nil;
|
||||
Class cls = [SizzleDeviceAU classForComponentType:kSizzleComponents[d->_index].type];
|
||||
SizzleDeviceAU *au = [[cls alloc] initWithComponentDescription:descFor(kSizzleComponents[d->_index]) options:0 error:&err];
|
||||
if (!au) { say([NSString stringWithFormat:@"%-16@ failed to load", d.name]); continue; }
|
||||
if (d.isInstrument) {
|
||||
((SizzleInstrumentAU *)au).sampleStore = &store();
|
||||
NSMutableDictionary *state = [au.fullState mutableCopy];
|
||||
NSMutableDictionary *values = [state[@"sizzleValues"] mutableCopy];
|
||||
for (int pad = 0; pad < 16; ++pad) values[[NSString stringWithFormat:@"pad%d", pad]] = @"bench";
|
||||
values[@"sfSample"] = @"bench";
|
||||
state[@"sizzleValues"] = values;
|
||||
au.fullState = state;
|
||||
}
|
||||
double secs = timeRender(au, d.isInstrument, 10.0);
|
||||
if (secs < 0) { say([NSString stringWithFormat:@"%-16@ failed to start", d.name]); continue; }
|
||||
say([NSString stringWithFormat:@"%-16@ %5.1f%% of a core%@", d.name, secs / 10.0 * 100.0,
|
||||
d.isInstrument ? @" (8 notes)" : @""]);
|
||||
}
|
||||
dispatch_async(dispatch_get_main_queue(), done);
|
||||
});
|
||||
}
|
||||
|
||||
@end
|
||||
Reference in New Issue
Block a user