// SPDX-License-Identifier: GPL-3.0-or-later #import #include "MacAudioOutput.h" #include #include namespace VCC::Mac { struct MacAudioOutput::Impl { std::shared_ptr ring = std::make_shared(); std::shared_ptr> changed = std::make_shared>(false); AVAudioEngine *engine = nil; id observer = nil; std::uint64_t starts = 0; ~Impl() { stop(); } void stop() { if(observer) { [[NSNotificationCenter defaultCenter] removeObserver:observer]; observer=nil; } [engine stop]; engine=nil; ring->clear(); changed->store(false); } }; MacAudioOutput::MacAudioOutput() : impl(std::make_unique()) {} MacAudioOutput::~MacAudioOutput() = default; AudioBuffer& MacAudioOutput::buffer() { return *impl->ring; } std::uint64_t MacAudioOutput::starts() const { return impl->starts; } bool MacAudioOutput::running() const { return impl->engine.isRunning; } bool MacAudioOutput::needsRestart() const { return impl->changed->load() || (impl->engine && !impl->engine.isRunning); } void MacAudioOutput::stop() { impl->stop(); } void MacAudioOutput::start() { if(running()) return; // A new graph follows the current default output device and its sample rate. impl->engine = [AVAudioEngine new]; AVAudioFormat *format = [[AVAudioFormat alloc] initStandardFormatWithSampleRate:44100 channels:2]; auto ring=impl->ring; AVAudioSourceNode *source = [[AVAudioSourceNode alloc] initWithFormat:format renderBlock: ^OSStatus(BOOL *silence, const AudioTimeStamp *, AVAudioFrameCount frames, AudioBufferList *list) { if(list->mNumberBuffers != 2) return kAudio_ParamError; ring->read(static_cast(list->mBuffers[0].mData),static_cast(list->mBuffers[1].mData),frames); *silence=NO; return noErr; }]; [impl->engine attachNode:source]; [impl->engine connect:source to:impl->engine.mainMixerNode format:format]; auto changed=impl->changed; impl->observer=[[NSNotificationCenter defaultCenter] addObserverForName:AVAudioEngineConfigurationChangeNotification object:impl->engine queue:nil usingBlock:^(NSNotification*) { changed->store(true); }]; NSError *error=nil; if(![impl->engine startAndReturnError:&error]) { const std::string message=error.localizedDescription.UTF8String ?: "Unable to start Mac audio output"; impl->stop(); throw std::runtime_error(message); } ++impl->starts; } }