// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown // SPDX-License-Identifier: GPL-3.0-or-later #import "SizzleEffectAU.h" #import "Components.gen.h" #import #include #include #include #include #include #include #include "sizzle/DeviceSpecs.gen.hpp" #include "sizzle/Effect.hpp" using namespace sizzle; namespace { /** * Everything the render thread touches, owned by the AU. * * Two ways settings reach the effect, neither of them locking: * - AU parameters (host automation, the UI) are written into [values] (one atomic * float per parameter, address = index in the spec) and bump [valuesSeq]; * - whole settings (presets, restored state, hidden keys such as the Mix * Tightener's) are written by the main thread into the spare half of [mailbox] * and published with [mailboxIdx] / [mailboxSeq]. * The render thread copies the published mailbox into [live], overlays the * parameter values, and calls Effect::update only when something changed. */ struct Kernel { const DeviceSpec *spec = nullptr; std::string type; std::unique_ptr fx[2]; int channels = 0; std::atomic values[Params::kMax]; std::atomic valuesSeq{1}; Params mailbox[2]; std::atomic mailboxIdx{0}; std::atomic mailboxSeq{1}; // render thread only Params live; uint32_t seenValues = 0, seenMailbox = 0; double tempo = 120.0; std::atomic bypass{false}; std::vector inBuf[2]; AUHostMusicalContextBlock musicalContext = nil; void publish(const Params &p) { int next = 1 - mailboxIdx.load(std::memory_order_acquire); mailbox[next] = p; mailboxIdx.store(next, std::memory_order_release); mailboxSeq.fetch_add(1, std::memory_order_release); } /** Parameter i's value as Params text: a choice name or a number. */ void overlay(Params &p) { for (int i = 0; i < spec->paramCount; ++i) { const ParamSpec &s = spec->params[i]; float v = values[i].load(std::memory_order_relaxed); if (s.isEnum()) { int n = s.choiceCount(), idx = (int)std::lround(v); p.set(s.key, s.choices[idx < 0 ? 0 : (idx >= n ? n - 1 : idx)]); } else { p.set(s.key, s.isInt ? std::round(v) : v); } } } /** Called at the top of each render cycle. */ void refresh(bool tempoChanged) { uint32_t ms = mailboxSeq.load(std::memory_order_acquire); uint32_t vs = valuesSeq.load(std::memory_order_acquire); if (ms == seenMailbox && vs == seenValues && !tempoChanged) return; if (ms != seenMailbox) live = mailbox[mailboxIdx.load(std::memory_order_acquire)]; seenMailbox = ms; seenValues = vs; overlay(live); for (int c = 0; c < channels; ++c) fx[c]->update(live, (float)tempo); } }; int choiceIndex(const ParamSpec &s, const char *name) { for (int i = 0; s.choices[i]; ++i) if (std::strcmp(s.choices[i], name) == 0) return i; return 0; } } // namespace @implementation SizzleEffectAU { std::unique_ptr _k; AUAudioUnitBusArray *_inputs; AUAudioUnitBusArray *_outputs; AUAudioUnitBus *_inBus; AUAudioUnitBus *_outBus; AUParameterTree *_tree; Params _base; // main thread: the full settings (incl. hidden keys) NSArray *_factoryPresets; AUAudioUnitPreset *_currentPreset; NSString *_displayName; } /// The standard initializer (used by AUAudioUnit registration and the Mac test): /// picks the device from the component's subtype in components.txt. - (instancetype)initWithComponentDescription:(AudioComponentDescription)desc options:(AudioComponentInstantiationOptions)options error:(NSError **)outError { for (int i = 0; i < kSizzleComponentCount; ++i) if (kSizzleComponents[i].subtype == desc.componentSubType) return [self initWithComponentDescription:desc toolboxType:kSizzleComponents[i].toolboxType displayName:@(kSizzleComponents[i].name) error:outError]; if (outError) *outError = [NSError errorWithDomain:NSOSStatusErrorDomain code:kAudioUnitErr_InvalidElement userInfo:nil]; return nil; } - (instancetype)initWithComponentDescription:(AudioComponentDescription)desc toolboxType:(const char *)toolboxType displayName:(NSString *)displayName error:(NSError **)outError { self = [super initWithComponentDescription:desc options:0 error:outError]; if (!self) return nil; _displayName = displayName; _k = std::make_unique(); _k->type = toolboxType; _k->spec = findDevice(toolboxType); if (!_k->spec) { if (outError) *outError = [NSError errorWithDomain:NSOSStatusErrorDomain code:kAudioUnitErr_InvalidProperty userInfo:nil]; return nil; } AVAudioFormat *fmt = [[AVAudioFormat alloc] initStandardFormatWithSampleRate:44100 channels:2]; _inBus = [[AUAudioUnitBus alloc] initWithFormat:fmt error:outError]; _outBus = [[AUAudioUnitBus alloc] initWithFormat:fmt error:outError]; if (!_inBus || !_outBus) return nil; _inBus.maximumChannelCount = 2; _outBus.maximumChannelCount = 2; _inputs = [[AUAudioUnitBusArray alloc] initWithAudioUnit:self busType:AUAudioUnitBusTypeInput busses:@[_inBus]]; _outputs = [[AUAudioUnitBusArray alloc] initWithAudioUnit:self busType:AUAudioUnitBusTypeOutput busses:@[_outBus]]; [self buildParameterTree]; _base.fill(*_k->spec); [self pushBase]; [self buildFactoryPresets]; self.maximumFramesToRender = 4096; return self; } - (NSString *)displayName { return _displayName; } #pragma mark - parameters - (void)buildParameterTree { const DeviceSpec *spec = _k->spec; NSMutableArray *params = [NSMutableArray array]; for (int i = 0; i < spec->paramCount; ++i) { const ParamSpec &s = spec->params[i]; AUParameter *p; AudioUnitParameterOptions flags = kAudioUnitParameterFlag_IsReadable | kAudioUnitParameterFlag_IsWritable; if (s.isEnum()) { NSMutableArray *names = [NSMutableArray array]; for (int c = 0; s.choices[c]; ++c) [names addObject:@(s.choices[c])]; p = [AUParameterTree createParameterWithIdentifier:@(s.key) name:@(s.label) address:(AUParameterAddress)i min:0 max:(AUValue)(names.count - 1) unit:kAudioUnitParameterUnit_Indexed unitName:nil flags:flags valueStrings:names dependentParameters:nil]; p.value = (AUValue)s.def; } else { p = [AUParameterTree createParameterWithIdentifier:@(s.key) name:@(s.label) address:(AUParameterAddress)i min:s.min max:s.max unit:s.isInt ? kAudioUnitParameterUnit_Indexed : kAudioUnitParameterUnit_Generic unitName:nil flags:flags valueStrings:nil dependentParameters:nil]; p.value = s.def; } _k->values[i].store(p.value); [params addObject:p]; } _tree = [AUParameterTree createTreeWithChildren:params]; Kernel *k = _k.get(); _tree.implementorValueObserver = ^(AUParameter *param, AUValue value) { if (param.address < (AUParameterAddress)k->spec->paramCount) { k->values[param.address].store(value, std::memory_order_relaxed); k->valuesSeq.fetch_add(1, std::memory_order_release); } }; _tree.implementorValueProvider = ^AUValue(AUParameter *param) { return param.address < (AUParameterAddress)k->spec->paramCount ? k->values[param.address].load() : 0; }; __weak SizzleEffectAU *weakSelf = self; _tree.implementorStringFromValueCallback = ^NSString *(AUParameter *param, const AUValue *value) { return [weakSelf stringForParameter:param value:value ? *value : param.value] ?: @""; }; } - (AUParameterTree *)parameterTree { return _tree; } /// Publish [_base] to the render thread and move the AU parameters to match it. - (void)pushBase { const DeviceSpec *spec = _k->spec; for (int i = 0; i < spec->paramCount; ++i) { const ParamSpec &s = spec->params[i]; AUValue v = s.isEnum() ? (AUValue)choiceIndex(s, _base.s(s.key, s.choices[0])) : _base.f(s.key, s.def); [_tree parameterWithAddress:(AUParameterAddress)i].value = v; // notifies UI + kernel } _k->publish(_base); } /// Bring [_base] up to date with the AU parameters (they're the source of truth for /// the visible keys; _base also holds hidden ones). - (void)pullBase { _k->overlay(_base); } - (NSString *)stringForParameter:(AUParameter *)param value:(AUValue)value { if (param.address >= (AUParameterAddress)_k->spec->paramCount) return @""; const ParamSpec &s = _k->spec->params[param.address]; if (s.isEnum()) { int n = s.choiceCount(), i = (int)std::lround(value); return @(s.choices[i < 0 ? 0 : (i >= n ? n - 1 : i)]); } const char *label = s.label; if (strstr(label, "(dB)")) return [NSString stringWithFormat:@"%.1f dB", value]; if (strstr(label, "(ms)")) return [NSString stringWithFormat:@"%.0f ms", value]; if (s.isInt) return s.min < 0 ? [NSString stringWithFormat:@"%+d", (int)std::lround(value)] : [NSString stringWithFormat:@"%d", (int)std::lround(value)]; if (s.min == 0 && s.max == 1) return [NSString stringWithFormat:@"%d%%", (int)std::lround(value * 100)]; if (s.min == -1 && s.max == 1) return [NSString stringWithFormat:@"%+d%%", (int)std::lround(value * 100)]; return [NSString stringWithFormat:@"%.2f", value]; } #pragma mark - presets and state - (void)buildFactoryPresets { NSMutableArray *list = [NSMutableArray array]; if (_k->type == "MIX_TIGHTENER") { for (int i = 0; gen::mixTightenerPresets[i]; ++i) { AUAudioUnitPreset *p = [AUAudioUnitPreset new]; p.number = i; p.name = @(gen::mixTightenerPresets[i][0]); [list addObject:p]; } } _factoryPresets = list; } - (NSArray *)factoryPresets { return _factoryPresets; } - (BOOL)supportsUserPresets { return YES; } - (AUAudioUnitPreset *)currentPreset { return _currentPreset; } - (void)setCurrentPreset:(AUAudioUnitPreset *)preset { if (preset == nil) { _currentPreset = nil; return; } if (preset.number >= 0) { if (preset.number < (NSInteger)_factoryPresets.count && _k->type == "MIX_TIGHTENER") { const char *const *kv = gen::mixTightenerPresets[preset.number]; _base.fill(*_k->spec); for (int i = 1; kv[i] && kv[i + 1]; i += 2) _base.set(kv[i], kv[i + 1]); [self pushBase]; } _currentPreset = preset; } else { NSError *err = nil; NSDictionary *state = [self presetStateFor:preset error:&err]; if (state) self.fullState = state; _currentPreset = preset; } } static NSString *const kStateKey = @"sizzleValues"; - (NSDictionary *)fullState { NSMutableDictionary *state = [NSMutableDictionary dictionaryWithDictionary:[super fullState] ?: @{}]; [self pullBase]; NSMutableDictionary *values = [NSMutableDictionary dictionary]; for (int i = 0; i < _base.size(); ++i) values[@(_base.keyAt(i))] = @(_base.valueAt(i)); state[kStateKey] = values; state[@"sizzleType"] = @(_k->type.c_str()); return state; } - (void)setFullState:(NSDictionary *)fullState { [super setFullState:fullState]; NSDictionary *values = fullState[kStateKey]; if (![values isKindOfClass:[NSDictionary class]]) return; _base.fill(*_k->spec); for (NSString *key in values) { id v = values[key]; if ([key isKindOfClass:[NSString class]] && [v isKindOfClass:[NSString class]]) _base.set(key.UTF8String, ((NSString *)v).UTF8String); } [self pushBase]; } #pragma mark - busses and render - (AUAudioUnitBusArray *)inputBusses { return _inputs; } - (AUAudioUnitBusArray *)outputBusses { return _outputs; } - (NSArray *)channelCapabilities { return @[@1, @1, @2, @2]; } - (BOOL)canProcessInPlace { return YES; } - (void)setShouldBypassEffect:(BOOL)bypass { [super setShouldBypassEffect:bypass]; _k->bypass.store(bypass); } - (BOOL)allocateRenderResourcesAndReturnError:(NSError **)outError { if (![super allocateRenderResourcesAndReturnError:outError]) return NO; AVAudioChannelCount chIn = _inBus.format.channelCount, chOut = _outBus.format.channelCount; if (chIn != chOut || chOut < 1 || chOut > 2) { if (outError) *outError = [NSError errorWithDomain:NSOSStatusErrorDomain code:kAudioUnitErr_FailedInitialization userInfo:nil]; self.renderResourcesAllocated = NO; return NO; } int sr = (int)std::lround(_outBus.format.sampleRate); Kernel *k = _k.get(); 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); } if (!k->fx[0]) { if (outError) *outError = [NSError errorWithDomain:NSOSStatusErrorDomain code:kAudioUnitErr_FailedInitialization userInfo:nil]; self.renderResourcesAllocated = NO; return NO; } k->musicalContext = self.musicalContextBlock; k->seenValues = k->seenMailbox = 0; // force update() on the first render return YES; } - (void)deallocateRenderResources { for (auto &f : _k->fx) f.reset(); _k->musicalContext = nil; [super deallocateRenderResources]; } - (AUInternalRenderBlock)internalRenderBlock { Kernel *k = _k.get(); return ^AUAudioUnitStatus(AudioUnitRenderActionFlags *actionFlags, const AudioTimeStamp *timestamp, AVAudioFrameCount frameCount, NSInteger outputBusNumber, AudioBufferList *outputData, const AURenderEvent *events, AURenderPullInputBlock pullInputBlock) { if (frameCount > k->inBuf[0].size() || !pullInputBlock) return kAudioUnitErr_TooManyFramesToProcess; // Pull the input into our own buffers. struct { AudioBufferList list; AudioBuffer extra; } in; in.list.mNumberBuffers = (UInt32)k->channels; for (int c = 0; c < k->channels; ++c) { in.list.mBuffers[c].mNumberChannels = 1; in.list.mBuffers[c].mDataByteSize = frameCount * sizeof(float); in.list.mBuffers[c].mData = k->inBuf[c].data(); } AudioUnitRenderActionFlags pullFlags = 0; AUAudioUnitStatus err = pullInputBlock(&pullFlags, timestamp, frameCount, 0, &in.list); if (err != noErr) return err; // Host automation arrives as render events: apply at block start. bool changed = false; for (const AURenderEvent *e = events; e; e = e->head.next) { if (e->head.eventType == AURenderEventParameter || e->head.eventType == AURenderEventParameterRamp) { AUParameterAddress a = e->parameter.parameterAddress; if (a < (AUParameterAddress)k->spec->paramCount) { k->values[a].store(e->parameter.value, std::memory_order_relaxed); changed = true; } } } if (changed) k->valuesSeq.fetch_add(1, std::memory_order_release); bool tempoChanged = false; if (k->musicalContext) { double bpm = 0; if (k->musicalContext(&bpm, nullptr, nullptr, nullptr, nullptr, nullptr) && bpm > 0 && bpm != k->tempo) { k->tempo = bpm; tempoChanged = true; } } k->refresh(tempoChanged); bool bypass = k->bypass.load(std::memory_order_relaxed); for (int c = 0; c < k->channels && c < (int)outputData->mNumberBuffers; ++c) { float *src = k->inBuf[c].data(); if (!outputData->mBuffers[c].mData) outputData->mBuffers[c].mData = src; // in place float *dst = (float *)outputData->mBuffers[c].mData; outputData->mBuffers[c].mDataByteSize = frameCount * sizeof(float); if (bypass) { if (dst != src) std::memcpy(dst, src, frameCount * sizeof(float)); continue; } Effect *fx = k->fx[c].get(); for (AVAudioFrameCount i = 0; i < frameCount; ++i) { float y = fx->process(src[i]); dst[i] = std::isfinite(y) ? y : 0.f; } } (void)actionFlags; (void)outputBusNumber; return noErr; }; } @end