From 1a973d685ef95390278d007b9978526ae136d9ec Mon Sep 17 00:00:00 2001 From: Andrew Belt Date: Wed, 5 Jan 2022 13:43:09 -0500 Subject: [PATCH] Initialize sample rate and block size of RtAudioDevice in constructor instead of openStream(). Fix algorithm to find closest allowed sample rate of device. --- src/rtaudio.cpp | 33 +++++++++++++++------------------ 1 file changed, 15 insertions(+), 18 deletions(-) diff --git a/src/rtaudio.cpp b/src/rtaudio.cpp index 12098ec0..5c079476 100644 --- a/src/rtaudio.cpp +++ b/src/rtaudio.cpp @@ -40,13 +40,21 @@ struct RtAudioDevice : audio::Device { RtAudio::StreamParameters inputParameters; RtAudio::StreamParameters outputParameters; RtAudio::StreamOptions options; - int blockSize = 0; - float sampleRate = 0; + int blockSize; + float sampleRate; RtAudioDevice(RtAudio::Api api, int deviceId) { this->api = api; this->deviceId = deviceId; + sampleRate = 44100; + + // DirectSound latency is too high for 256 block size. + if (api == RtAudio::WINDOWS_DS) + blockSize = 1024; + else + blockSize = 256; + // Create RtAudio object INFO("Creating RtAudio %s context", RTAUDIO_API_NAMES.at(api).c_str()); try { @@ -102,25 +110,14 @@ struct RtAudioDevice : audio::Device { options.numberOfBuffers = 2; options.streamName = "VCV Rack"; - // Most people prefer 44100 default sample rate although many devices report 48000 from `deviceInfo.preferredSampleRate`. - float closestSampleRate = 44100; - if (sampleRate > 0) { - // Find the closest sample rate to the requested one. - for (float sr : deviceInfo.sampleRates) { - if (std::fabs(sr - sampleRate) < std::fabs(closestSampleRate - sampleRate)) { - closestSampleRate = sr; - } + float closestSampleRate = INFINITY; + // Find the closest sample rate to the requested one. + for (float sr : deviceInfo.sampleRates) { + if (std::fabs(sr - sampleRate) < std::fabs(closestSampleRate - sampleRate)) { + closestSampleRate = sr; } } - if (blockSize <= 0) { - // DirectSound should use a higher default block size - if (api == RtAudio::WINDOWS_DS) - blockSize = 1024; - else - blockSize = 256; - } - INFO("Opening RtAudio %s device %d: %s (%d in, %d out, %g sample rate, %d block size)", RTAUDIO_API_NAMES.at(api).c_str(), deviceId, deviceInfo.name.c_str(), inputParameters.nChannels, outputParameters.nChannels, closestSampleRate, blockSize); try { rtAudio->openStream(