51 lines
2.5 KiB
Plaintext
51 lines
2.5 KiB
Plaintext
// SPDX-License-Identifier: GPL-3.0-or-later
|
|
#import <AVFoundation/AVFoundation.h>
|
|
#include "MacAudioOutput.h"
|
|
#include <stdexcept>
|
|
#include <string>
|
|
namespace VCC::Mac {
|
|
struct MacAudioOutput::Impl {
|
|
std::shared_ptr<AudioBuffer> ring = std::make_shared<AudioBuffer>();
|
|
std::shared_ptr<std::atomic<bool>> changed = std::make_shared<std::atomic<bool>>(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<Impl>()) {}
|
|
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<float*>(list->mBuffers[0].mData),static_cast<float*>(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;
|
|
}
|
|
}
|