From 859319fa7864ed6a81af1f12c68627ab58bb7a7d Mon Sep 17 00:00:00 2001 From: Chris Robinson Date: Sun, 3 Dec 2023 14:31:24 -0800 Subject: Replace a global function with a member function --- alc/backends/pulseaudio.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'alc/backends/pulseaudio.cpp') diff --git a/alc/backends/pulseaudio.cpp b/alc/backends/pulseaudio.cpp index bebc182d..2f0e7a84 100644 --- a/alc/backends/pulseaudio.cpp +++ b/alc/backends/pulseaudio.cpp @@ -1034,7 +1034,7 @@ ClockLatency PulsePlayback::getClockLatency() { MainloopUniqueLock plock{mMainloop}; - ret.ClockTime = GetDeviceClockTime(mDevice); + ret.ClockTime = mDevice->getClockTime(); err = pa_stream_get_latency(mStream, &latency, &neg); } @@ -1362,7 +1362,7 @@ ClockLatency PulseCapture::getClockLatency() { MainloopUniqueLock plock{mMainloop}; - ret.ClockTime = GetDeviceClockTime(mDevice); + ret.ClockTime = mDevice->getClockTime(); err = pa_stream_get_latency(mStream, &latency, &neg); } -- cgit v1.2.3 From 60aa22f20d63a3da9f06b9398a2a8656ebbd0342 Mon Sep 17 00:00:00 2001 From: Chris Robinson Date: Mon, 11 Dec 2023 18:59:54 -0800 Subject: Mostly finish cleanup for backends Except CoreAudio and Solaris backends --- alc/backends/alsa.cpp | 20 ++++++++++--------- alc/backends/dsound.cpp | 4 ++-- alc/backends/jack.cpp | 3 ++- alc/backends/oboe.cpp | 8 ++++---- alc/backends/opensl.cpp | 3 ++- alc/backends/oss.cpp | 4 +++- alc/backends/pulseaudio.cpp | 29 +++++++++++++++++---------- alc/backends/sndio.cpp | 21 ++++++++++---------- alc/backends/solaris.cpp | 16 +++++++-------- alc/backends/wasapi.cpp | 48 +++++++++++++++++++++++++-------------------- alc/backends/wave.cpp | 35 ++++++++++++++++----------------- alc/backends/winmm.cpp | 8 ++++---- alc/context.cpp | 8 ++++++-- 13 files changed, 116 insertions(+), 91 deletions(-) (limited to 'alc/backends/pulseaudio.cpp') diff --git a/alc/backends/alsa.cpp b/alc/backends/alsa.cpp index 47c6385e..fa34e4f9 100644 --- a/alc/backends/alsa.cpp +++ b/alc/backends/alsa.cpp @@ -53,6 +53,7 @@ namespace { +/* NOLINTNEXTLINE(*-avoid-c-arrays) */ constexpr char alsaDevice[] = "ALSA Default"; @@ -715,17 +716,18 @@ bool AlsaPlayback::reset() /* test and set format (implicitly sets sample bits) */ if(snd_pcm_hw_params_test_format(mPcmHandle, hp.get(), format) < 0) { - static const struct { + struct FormatMap { snd_pcm_format_t format; DevFmtType fmttype; - } formatlist[] = { - { SND_PCM_FORMAT_FLOAT, DevFmtFloat }, - { SND_PCM_FORMAT_S32, DevFmtInt }, - { SND_PCM_FORMAT_U32, DevFmtUInt }, - { SND_PCM_FORMAT_S16, DevFmtShort }, - { SND_PCM_FORMAT_U16, DevFmtUShort }, - { SND_PCM_FORMAT_S8, DevFmtByte }, - { SND_PCM_FORMAT_U8, DevFmtUByte }, + }; + static constexpr std::array formatlist{ + FormatMap{SND_PCM_FORMAT_FLOAT, DevFmtFloat }, + FormatMap{SND_PCM_FORMAT_S32, DevFmtInt }, + FormatMap{SND_PCM_FORMAT_U32, DevFmtUInt }, + FormatMap{SND_PCM_FORMAT_S16, DevFmtShort }, + FormatMap{SND_PCM_FORMAT_U16, DevFmtUShort}, + FormatMap{SND_PCM_FORMAT_S8, DevFmtByte }, + FormatMap{SND_PCM_FORMAT_U8, DevFmtUByte }, }; for(const auto &fmt : formatlist) diff --git a/alc/backends/dsound.cpp b/alc/backends/dsound.cpp index 12196f74..08c849e9 100644 --- a/alc/backends/dsound.cpp +++ b/alc/backends/dsound.cpp @@ -35,11 +35,11 @@ #include #include #include +#include +#include #include #include #include -#include -#include #include #include #include diff --git a/alc/backends/jack.cpp b/alc/backends/jack.cpp index ca862276..1a53da17 100644 --- a/alc/backends/jack.cpp +++ b/alc/backends/jack.cpp @@ -102,6 +102,7 @@ decltype(jack_error_callback) * pjack_error_callback; #endif +/* NOLINTNEXTLINE(*-avoid-c-arrays) */ constexpr char JackDefaultAudioType[] = JACK_DEFAULT_AUDIO_TYPE; jack_options_t ClientOptions = JackNullOption; @@ -158,7 +159,7 @@ bool jack_load() struct JackDeleter { void operator()(void *ptr) { jack_free(ptr); } }; -using JackPortsPtr = std::unique_ptr; +using JackPortsPtr = std::unique_ptr; /* NOLINT(*-avoid-c-arrays) */ struct DeviceEntry { std::string mName; diff --git a/alc/backends/oboe.cpp b/alc/backends/oboe.cpp index 9666063a..1076bc8d 100644 --- a/alc/backends/oboe.cpp +++ b/alc/backends/oboe.cpp @@ -4,8 +4,8 @@ #include "oboe.h" #include +#include #include -#include #include "alnumeric.h" #include "core/device.h" @@ -17,6 +17,7 @@ namespace { +/* NOLINTNEXTLINE(*-avoid-c-arrays) */ constexpr char device_name[] = "Oboe Default"; @@ -48,11 +49,10 @@ oboe::DataCallbackResult OboePlayback::onAudioReady(oboe::AudioStream *oboeStrea return oboe::DataCallbackResult::Continue; } -void OboePlayback::onErrorAfterClose(oboe::AudioStream* audioStream, oboe::Result error) +void OboePlayback::onErrorAfterClose(oboe::AudioStream*, oboe::Result error) { - if (error == oboe::Result::ErrorDisconnected) { + if(error == oboe::Result::ErrorDisconnected) mDevice->handleDisconnect("Oboe AudioStream was disconnected: %s", oboe::convertToText(error)); - } TRACE("Error was %s", oboe::convertToText(error)); } diff --git a/alc/backends/opensl.cpp b/alc/backends/opensl.cpp index 3d99e93f..75b6e30d 100644 --- a/alc/backends/opensl.cpp +++ b/alc/backends/opensl.cpp @@ -23,10 +23,10 @@ #include "opensl.h" -#include #include #include +#include #include #include #include @@ -56,6 +56,7 @@ namespace { #define VCALL0(obj, func) ((*(obj))->func((obj) EXTRACT_VCALL_ARGS +/* NOLINTNEXTLINE(*-avoid-c-arrays) */ constexpr char opensl_device[] = "OpenSL"; diff --git a/alc/backends/oss.cpp b/alc/backends/oss.cpp index 010b0749..e6cebec4 100644 --- a/alc/backends/oss.cpp +++ b/alc/backends/oss.cpp @@ -79,7 +79,9 @@ namespace { +/* NOLINTNEXTLINE(*-avoid-c-arrays) */ constexpr char DefaultName[] = "OSS Default"; + std::string DefaultPlayback{"/dev/dsp"}; std::string DefaultCapture{"/dev/dsp"}; @@ -379,7 +381,7 @@ bool OSSPlayback::reset() CHECKERR(ioctl(mFd, SNDCTL_DSP_CHANNELS, &numChannels)); CHECKERR(ioctl(mFd, SNDCTL_DSP_SPEED, &ossSpeed)); CHECKERR(ioctl(mFd, SNDCTL_DSP_GETOSPACE, &info)); - if(0) + if(false) { err: ERR("%s failed: %s\n", err, strerror(errno)); diff --git a/alc/backends/pulseaudio.cpp b/alc/backends/pulseaudio.cpp index 2f0e7a84..b6f0f95d 100644 --- a/alc/backends/pulseaudio.cpp +++ b/alc/backends/pulseaudio.cpp @@ -28,12 +28,12 @@ #include #include #include +#include +#include #include #include #include #include -#include -#include #include #include #include @@ -320,11 +320,12 @@ public: explicit operator bool() const noexcept { return mLoop != nullptr; } + [[nodiscard]] auto start() const { return pa_threaded_mainloop_start(mLoop); } auto stop() const { return pa_threaded_mainloop_stop(mLoop); } - auto getApi() const { return pa_threaded_mainloop_get_api(mLoop); } - auto getContext() const noexcept { return mContext; } + [[nodiscard]] auto getApi() const { return pa_threaded_mainloop_get_api(mLoop); } + [[nodiscard]] auto getContext() const noexcept { return mContext; } auto lock() const { return pa_threaded_mainloop_lock(mLoop); } auto unlock() const { return pa_threaded_mainloop_unlock(mLoop); } @@ -753,9 +754,9 @@ void PulsePlayback::sinkInfoCallback(pa_context*, const pa_sink_info *info, int else { mIs51Rear = false; - char chanmap_str[PA_CHANNEL_MAP_SNPRINT_MAX]{}; - pa_channel_map_snprint(chanmap_str, sizeof(chanmap_str), &info->channel_map); - WARN("Failed to find format for channel map:\n %s\n", chanmap_str); + std::array chanmap_str{}; + pa_channel_map_snprint(chanmap_str.data(), chanmap_str.size(), &info->channel_map); + WARN("Failed to find format for channel map:\n %s\n", chanmap_str.data()); } if(info->active_port) @@ -784,7 +785,9 @@ void PulsePlayback::streamMovedCallback(pa_stream *stream) noexcept void PulsePlayback::open(std::string_view name) { mMainloop = PulseMainloop::Create(); - mMainloop.start(); + if(mMainloop.start() != 0) + throw al::backend_exception{al::backend_error::DeviceError, + "Failed to start device mainloop"}; const char *pulse_name{nullptr}; const char *dev_name{nullptr}; @@ -1127,7 +1130,9 @@ void PulseCapture::open(std::string_view name) if(!mMainloop) { mMainloop = PulseMainloop::Create(); - mMainloop.start(); + if(mMainloop.start() != 0) + throw al::backend_exception{al::backend_error::DeviceError, + "Failed to start device mainloop"}; } const char *pulse_name{nullptr}; @@ -1432,7 +1437,11 @@ bool PulseBackendFactory::init() if(!gGlobalMainloop) { gGlobalMainloop = PulseMainloop::Create(); - gGlobalMainloop.start(); + if(gGlobalMainloop.start() != 0) + { + gGlobalMainloop = nullptr; + return false; + } } MainloopUniqueLock plock{gGlobalMainloop}; diff --git a/alc/backends/sndio.cpp b/alc/backends/sndio.cpp index 8bf63a59..d05db2e8 100644 --- a/alc/backends/sndio.cpp +++ b/alc/backends/sndio.cpp @@ -23,11 +23,11 @@ #include "sndio.h" #include +#include +#include +#include #include #include -#include -#include -#include #include #include @@ -43,7 +43,8 @@ namespace { -static const char sndio_device[] = "SndIO Default"; +/* NOLINTNEXTLINE(*-avoid-c-arrays) */ +constexpr char sndio_device[] = "SndIO Default"; struct SioPar : public sio_par { SioPar() { sio_initpar(this); } @@ -317,19 +318,19 @@ int SndioCapture::recordProc() return 1; } - auto fds = std::make_unique(static_cast(nfds_pre)); + auto fds = std::vector(static_cast(nfds_pre)); while(!mKillNow.load(std::memory_order_acquire) && mDevice->Connected.load(std::memory_order_acquire)) { /* Wait until there's some samples to read. */ - const int nfds{sio_pollfd(mSndHandle, fds.get(), POLLIN)}; + const int nfds{sio_pollfd(mSndHandle, fds.data(), POLLIN)}; if(nfds <= 0) { mDevice->handleDisconnect("Failed to get polling fds: %d", nfds); break; } - int pollres{::poll(fds.get(), static_cast(nfds), 2000)}; + int pollres{::poll(fds.data(), fds.size(), 2000)}; if(pollres < 0) { if(errno == EINTR) continue; @@ -339,7 +340,7 @@ int SndioCapture::recordProc() if(pollres == 0) continue; - const int revents{sio_revents(mSndHandle, fds.get())}; + const int revents{sio_revents(mSndHandle, fds.data())}; if((revents&POLLHUP)) { mDevice->handleDisconnect("Got POLLHUP from poll events"); @@ -373,8 +374,8 @@ int SndioCapture::recordProc() if(buffer.empty()) { /* Got samples to read, but no place to store it. Drop it. */ - static char junk[4096]; - sio_read(mSndHandle, junk, sizeof(junk) - (sizeof(junk)%frameSize)); + static std::array junk; + sio_read(mSndHandle, junk.data(), junk.size() - (junk.size()%frameSize)); } } diff --git a/alc/backends/solaris.cpp b/alc/backends/solaris.cpp index 38f9db19..2c4a97fd 100644 --- a/alc/backends/solaris.cpp +++ b/alc/backends/solaris.cpp @@ -51,6 +51,7 @@ namespace { +/* NOLINTNEXTLINE(*-avoid-c-arrays) */ constexpr char solaris_device[] = "Solaris Default"; std::string solaris_driver{"/dev/audio"}; @@ -91,7 +92,7 @@ int SolarisBackend::mixerProc() althrd_setname(MIXER_THREAD_NAME); const size_t frame_step{mDevice->channelsFromFmt()}; - const uint frame_size{mDevice->frameSizeFromFmt()}; + const size_t frame_size{mDevice->frameSizeFromFmt()}; while(!mKillNow.load(std::memory_order_acquire) && mDevice->Connected.load(std::memory_order_acquire)) @@ -115,12 +116,12 @@ int SolarisBackend::mixerProc() continue; } - std::byte *write_ptr{mBuffer.data()}; - size_t to_write{mBuffer.size()}; - mDevice->renderSamples(write_ptr, static_cast(to_write/frame_size), frame_step); - while(to_write > 0 && !mKillNow.load(std::memory_order_acquire)) + al::span buffer{mBuffer}; + mDevice->renderSamples(buffer.data(), static_cast(buffer.size()/frame_size), + frame_step); + while(!buffer.empty() && !mKillNow.load(std::memory_order_acquire)) { - ssize_t wrote{write(mFd, write_ptr, to_write)}; + ssize_t wrote{write(mFd, buffer.data(), buffer.size())}; if(wrote < 0) { if(errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) @@ -130,8 +131,7 @@ int SolarisBackend::mixerProc() break; } - to_write -= static_cast(wrote); - write_ptr += wrote; + buffer = buffer.subspan(static_cast(wrote)); } } diff --git a/alc/backends/wasapi.cpp b/alc/backends/wasapi.cpp index 139fa696..3e9632e0 100644 --- a/alc/backends/wasapi.cpp +++ b/alc/backends/wasapi.cpp @@ -25,8 +25,8 @@ #define WIN32_LEAN_AND_MEAN #include -#include -#include +#include +#include #include #include @@ -171,7 +171,7 @@ constexpr AudioObjectType ChannelMask_X714{AudioObjectType_FrontLeft | AudioObje | AudioObjectType_TopFrontLeft | AudioObjectType_TopFrontRight | AudioObjectType_TopBackLeft | AudioObjectType_TopBackRight}; - +/* NOLINTNEXTLINE(*-avoid-c-arrays) */ constexpr char DevNameHead[] = "OpenAL Soft on "; constexpr size_t DevNameHeadLen{std::size(DevNameHead) - 1}; @@ -201,16 +201,16 @@ constexpr uint RefTime2Samples(const ReferenceTime &val, T srate) noexcept class GuidPrinter { - char mMsg[64]; + std::array mMsg; public: GuidPrinter(const GUID &guid) { - std::snprintf(mMsg, std::size(mMsg), "{%08lx-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x}", + std::snprintf(mMsg.data(), mMsg.size(), "{%08lx-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x}", DWORD{guid.Data1}, guid.Data2, guid.Data3, guid.Data4[0], guid.Data4[1], guid.Data4[2], guid.Data4[3], guid.Data4[4], guid.Data4[5], guid.Data4[6], guid.Data4[7]); } - const char *c_str() const { return mMsg; } + [[nodiscard]] auto c_str() const -> const char* { return mMsg.data(); } }; struct PropVariant { @@ -270,13 +270,13 @@ private: struct DeviceListLock : public std::unique_lock { using std::unique_lock::unique_lock; - auto& getPlaybackList() const noexcept { return mutex()->mPlayback; } - auto& getCaptureList() const noexcept { return mutex()->mCapture; } + [[nodiscard]] auto& getPlaybackList() const noexcept { return mutex()->mPlayback; } + [[nodiscard]] auto& getCaptureList() const noexcept { return mutex()->mCapture; } void setPlaybackDefaultId(std::wstring_view devid) const { mutex()->mPlaybackDefaultId = devid; } - std::wstring_view getPlaybackDefaultId() const noexcept { return mutex()->mPlaybackDefaultId; } + [[nodiscard]] auto getPlaybackDefaultId() const noexcept -> std::wstring_view { return mutex()->mPlaybackDefaultId; } void setCaptureDefaultId(std::wstring_view devid) const { mutex()->mCaptureDefaultId = devid; } - std::wstring_view getCaptureDefaultId() const noexcept { return mutex()->mCaptureDefaultId; } + [[nodiscard]] auto getCaptureDefaultId() const noexcept -> std::wstring_view { return mutex()->mCaptureDefaultId; } }; DeviceList gDeviceList; @@ -302,8 +302,10 @@ using DeviceHandle = ComPtr; using NameGUIDPair = std::pair; static NameGUIDPair GetDeviceNameAndGuid(const DeviceHandle &device) { + /* NOLINTBEGIN(*-avoid-c-arrays) */ static constexpr char UnknownName[]{"Unknown Device Name"}; static constexpr char UnknownGuid[]{"Unknown Device GUID"}; + /* NOLINTEND(*-avoid-c-arrays) */ #if !defined(ALSOFT_UWP) std::string name, guid; @@ -384,9 +386,9 @@ struct DeviceHelper final : public IActivateAudioInterfaceCompletionHandler struct DeviceHelper final : private IMMNotificationClient #endif { +#if defined(ALSOFT_UWP) DeviceHelper() { -#if defined(ALSOFT_UWP) /* TODO: UWP also needs to watch for device added/removed events and * dynamically add/remove devices from the lists. */ @@ -411,8 +413,10 @@ struct DeviceHelper final : private IMMNotificationClient msg); } }); -#endif } +#else + DeviceHelper() = default; +#endif ~DeviceHelper() { #if defined(ALSOFT_UWP) @@ -1071,7 +1075,7 @@ struct WasapiPlayback final : public BackendBase, WasapiProxy { HANDLE mNotifyEvent{nullptr}; UINT32 mOrigBufferSize{}, mOrigUpdateSize{}; - std::unique_ptr mResampleBuffer{}; + std::vector mResampleBuffer{}; uint mBufferFilled{0}; SampleConverterPtr mResampler; @@ -1151,9 +1155,9 @@ FORCE_ALIGN int WasapiPlayback::mixerProc() { if(mBufferFilled == 0) { - mDevice->renderSamples(mResampleBuffer.get(), mDevice->UpdateSize, + mDevice->renderSamples(mResampleBuffer.data(), mDevice->UpdateSize, mFormat.Format.nChannels); - resbufferptr = mResampleBuffer.get(); + resbufferptr = mResampleBuffer.data(); mBufferFilled = mDevice->UpdateSize; } @@ -1249,7 +1253,7 @@ FORCE_ALIGN int WasapiPlayback::mixerSpatialProc() tmpbuffers.resize(buffers.size()); resbuffers.resize(buffers.size()); for(size_t i{0};i < tmpbuffers.size();++i) - resbuffers[i] = reinterpret_cast(mResampleBuffer.get()) + + resbuffers[i] = reinterpret_cast(mResampleBuffer.data()) + mDevice->UpdateSize*i; } } @@ -1819,7 +1823,8 @@ HRESULT WasapiPlayback::resetProxy() mDevice->BufferSize = mDevice->UpdateSize*2; mResampler = nullptr; - mResampleBuffer = nullptr; + mResampleBuffer.clear(); + mResampleBuffer.shrink_to_fit(); mBufferFilled = 0; if(mDevice->Frequency != mFormat.Format.nSamplesPerSec) { @@ -1828,7 +1833,7 @@ HRESULT WasapiPlayback::resetProxy() mResampler = SampleConverter::Create(mDevice->FmtType, mDevice->FmtType, channelCount, mDevice->Frequency, mFormat.Format.nSamplesPerSec, Resampler::FastBSinc24); - mResampleBuffer = std::make_unique(size_t{mDevice->UpdateSize} * channelCount * + mResampleBuffer.resize(size_t{mDevice->UpdateSize} * channelCount * mFormat.Format.wBitsPerSample / 8); TRACE("Created converter for %s/%s format, dst: %luhz (%u), src: %uhz (%u)\n", @@ -1950,15 +1955,16 @@ no_spatial: mDevice->BufferSize/2); mResampler = nullptr; - mResampleBuffer = nullptr; + mResampleBuffer.clear(); + mResampleBuffer.shrink_to_fit(); mBufferFilled = 0; if(mDevice->Frequency != mFormat.Format.nSamplesPerSec) { mResampler = SampleConverter::Create(mDevice->FmtType, mDevice->FmtType, mFormat.Format.nChannels, mDevice->Frequency, mFormat.Format.nSamplesPerSec, Resampler::FastBSinc24); - mResampleBuffer = std::make_unique(size_t{mDevice->UpdateSize} * - mFormat.Format.nChannels * mFormat.Format.wBitsPerSample / 8); + mResampleBuffer.resize(size_t{mDevice->UpdateSize} * mFormat.Format.nChannels * + mFormat.Format.wBitsPerSample / 8); TRACE("Created converter for %s/%s format, dst: %luhz (%u), src: %uhz (%u)\n", DevFmtChannelsString(mDevice->FmtChans), DevFmtTypeString(mDevice->FmtType), diff --git a/alc/backends/wave.cpp b/alc/backends/wave.cpp index 794d5cb8..f3261ed4 100644 --- a/alc/backends/wave.cpp +++ b/alc/backends/wave.cpp @@ -55,38 +55,39 @@ using std::chrono::nanoseconds; using ubyte = unsigned char; using ushort = unsigned short; +/* NOLINTNEXTLINE(*-avoid-c-arrays) */ constexpr char waveDevice[] = "Wave File Writer"; -constexpr ubyte SUBTYPE_PCM[]{ +constexpr std::array SUBTYPE_PCM{{ 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 -}; -constexpr ubyte SUBTYPE_FLOAT[]{ +}}; +constexpr std::array SUBTYPE_FLOAT{{ 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 -}; +}}; -constexpr ubyte SUBTYPE_BFORMAT_PCM[]{ +constexpr std::array SUBTYPE_BFORMAT_PCM{{ 0x01, 0x00, 0x00, 0x00, 0x21, 0x07, 0xd3, 0x11, 0x86, 0x44, 0xc8, 0xc1, 0xca, 0x00, 0x00, 0x00 -}; +}}; -constexpr ubyte SUBTYPE_BFORMAT_FLOAT[]{ +constexpr std::array SUBTYPE_BFORMAT_FLOAT{{ 0x03, 0x00, 0x00, 0x00, 0x21, 0x07, 0xd3, 0x11, 0x86, 0x44, 0xc8, 0xc1, 0xca, 0x00, 0x00, 0x00 -}; +}}; void fwrite16le(ushort val, FILE *f) { - ubyte data[2]{ static_cast(val&0xff), static_cast((val>>8)&0xff) }; - fwrite(data, 1, 2, f); + std::array data{static_cast(val&0xff), static_cast((val>>8)&0xff)}; + fwrite(data.data(), 1, data.size(), f); } void fwrite32le(uint val, FILE *f) { - ubyte data[4]{ static_cast(val&0xff), static_cast((val>>8)&0xff), - static_cast((val>>16)&0xff), static_cast((val>>24)&0xff) }; - fwrite(data, 1, 4, f); + std::array data{static_cast(val&0xff), static_cast((val>>8)&0xff), + static_cast((val>>16)&0xff), static_cast((val>>24)&0xff)}; + fwrite(data.data(), 1, data.size(), f); } @@ -228,7 +229,6 @@ bool WaveBackend::reset() { uint channels{0}, bytes{0}, chanmask{0}; bool isbformat{false}; - size_t val; fseek(mFile, 0, SEEK_SET); clearerr(mFile); @@ -311,10 +311,9 @@ bool WaveBackend::reset() // 32-bit val, channel mask fwrite32le(chanmask, mFile); // 16 byte GUID, sub-type format - val = fwrite((mDevice->FmtType == DevFmtFloat) ? - (isbformat ? SUBTYPE_BFORMAT_FLOAT : SUBTYPE_FLOAT) : - (isbformat ? SUBTYPE_BFORMAT_PCM : SUBTYPE_PCM), 1, 16, mFile); - (void)val; + std::ignore = fwrite((mDevice->FmtType == DevFmtFloat) ? + (isbformat ? SUBTYPE_BFORMAT_FLOAT.data() : SUBTYPE_FLOAT.data()) : + (isbformat ? SUBTYPE_BFORMAT_PCM.data() : SUBTYPE_PCM.data()), 1, 16, mFile); fputs("data", mFile); fwrite32le(0xFFFFFFFF, mFile); // 'data' header len; filled in at close diff --git a/alc/backends/winmm.cpp b/alc/backends/winmm.cpp index 15776d17..696f7f37 100644 --- a/alc/backends/winmm.cpp +++ b/alc/backends/winmm.cpp @@ -22,8 +22,8 @@ #include "winmm.h" -#include -#include +#include +#include #include #include @@ -62,7 +62,7 @@ std::vector CaptureDevices; bool checkName(const std::vector &list, const std::string &name) { return std::find(list.cbegin(), list.cend(), name) != list.cend(); } -void ProbePlaybackDevices(void) +void ProbePlaybackDevices() { PlaybackDevices.clear(); @@ -93,7 +93,7 @@ void ProbePlaybackDevices(void) } } -void ProbeCaptureDevices(void) +void ProbeCaptureDevices() { CaptureDevices.clear(); diff --git a/alc/context.cpp b/alc/context.cpp index 92e458cb..2def58ba 100644 --- a/alc/context.cpp +++ b/alc/context.cpp @@ -164,9 +164,13 @@ void ALCcontext::init() else { auxslots = EffectSlot::CreatePtrArray(1); - (*auxslots)[0] = mDefaultSlot->mSlot; - mDefaultSlot->mState = SlotState::Playing; + if(auxslots) + { + (*auxslots)[0] = mDefaultSlot->mSlot; + mDefaultSlot->mState = SlotState::Playing; + } } + if(!auxslots) throw std::bad_alloc{}; mActiveAuxSlots.store(auxslots, std::memory_order_relaxed); allocVoiceChanges(); -- cgit v1.2.3 From bc83c874ff15b29fdab9b6c0bf40b268345b3026 Mon Sep 17 00:00:00 2001 From: Chris Robinson Date: Sat, 16 Dec 2023 17:48:33 -0800 Subject: Remove DEF_NEWDEL C++17 provides alignment-aware allocators for us, so we don't need to use our own to make sure classes/structs are properly aligned. --- al/auxeffectslot.h | 3 --- alc/backends/alsa.cpp | 4 ---- alc/backends/coreaudio.cpp | 4 ---- alc/backends/dsound.cpp | 4 ---- alc/backends/jack.cpp | 2 -- alc/backends/loopback.cpp | 2 -- alc/backends/null.cpp | 2 -- alc/backends/opensl.cpp | 4 ---- alc/backends/oss.cpp | 4 ---- alc/backends/pipewire.cpp | 4 ---- alc/backends/portaudio.cpp | 4 ---- alc/backends/pulseaudio.cpp | 4 ---- alc/backends/sdl2.cpp | 2 -- alc/backends/sndio.cpp | 4 ---- alc/backends/solaris.cpp | 2 -- alc/backends/wasapi.cpp | 4 ---- alc/backends/wave.cpp | 2 -- alc/backends/winmm.cpp | 4 ---- alc/context.h | 2 -- alc/device.h | 2 -- alc/effects/autowah.cpp | 2 -- alc/effects/chorus.cpp | 2 -- alc/effects/compressor.cpp | 2 -- alc/effects/convolution.cpp | 2 -- alc/effects/dedicated.cpp | 2 -- alc/effects/distortion.cpp | 2 -- alc/effects/echo.cpp | 2 -- alc/effects/equalizer.cpp | 2 -- alc/effects/fshifter.cpp | 2 -- alc/effects/modulator.cpp | 2 -- alc/effects/null.cpp | 2 -- alc/effects/pshifter.cpp | 2 -- alc/effects/reverb.cpp | 2 -- alc/effects/vmorpher.cpp | 2 -- common/almalloc.h | 13 ------------- core/bformatdec.h | 2 -- core/context.h | 6 ++---- core/device.h | 2 -- core/effectslot.h | 4 ---- core/uhjfilter.h | 10 ---------- core/voice.h | 4 ---- core/voice_change.h | 4 ---- utils/uhjdecoder.cpp | 3 --- utils/uhjencoder.cpp | 3 --- 44 files changed, 2 insertions(+), 140 deletions(-) (limited to 'alc/backends/pulseaudio.cpp') diff --git a/al/auxeffectslot.h b/al/auxeffectslot.h index bfd4038e..fc474bb4 100644 --- a/al/auxeffectslot.h +++ b/al/auxeffectslot.h @@ -81,9 +81,6 @@ struct ALeffectslot { static void SetName(ALCcontext *context, ALuint id, std::string_view name); - /* This can be new'd for the context's default effect slot. */ - DEF_NEWDEL(ALeffectslot) - #ifdef ALSOFT_EAX public: diff --git a/alc/backends/alsa.cpp b/alc/backends/alsa.cpp index fa34e4f9..344c440c 100644 --- a/alc/backends/alsa.cpp +++ b/alc/backends/alsa.cpp @@ -444,8 +444,6 @@ struct AlsaPlayback final : public BackendBase { std::atomic mKillNow{true}; std::thread mThread; - - DEF_NEWDEL(AlsaPlayback) }; AlsaPlayback::~AlsaPlayback() @@ -888,8 +886,6 @@ struct AlsaCapture final : public BackendBase { RingBufferPtr mRing{nullptr}; snd_pcm_sframes_t mLastAvail{0}; - - DEF_NEWDEL(AlsaCapture) }; AlsaCapture::~AlsaCapture() diff --git a/alc/backends/coreaudio.cpp b/alc/backends/coreaudio.cpp index 50e3bc66..86c4b89b 100644 --- a/alc/backends/coreaudio.cpp +++ b/alc/backends/coreaudio.cpp @@ -337,8 +337,6 @@ struct CoreAudioPlayback final : public BackendBase { uint mFrameSize{0u}; AudioStreamBasicDescription mFormat{}; // This is the OpenAL format as a CoreAudio ASBD - - DEF_NEWDEL(CoreAudioPlayback) }; CoreAudioPlayback::~CoreAudioPlayback() @@ -623,8 +621,6 @@ struct CoreAudioCapture final : public BackendBase { std::vector mCaptureData; RingBufferPtr mRing{nullptr}; - - DEF_NEWDEL(CoreAudioCapture) }; CoreAudioCapture::~CoreAudioCapture() diff --git a/alc/backends/dsound.cpp b/alc/backends/dsound.cpp index 08c849e9..59a59a9f 100644 --- a/alc/backends/dsound.cpp +++ b/alc/backends/dsound.cpp @@ -191,8 +191,6 @@ struct DSoundPlayback final : public BackendBase { std::atomic mKillNow{true}; std::thread mThread; - - DEF_NEWDEL(DSoundPlayback) }; DSoundPlayback::~DSoundPlayback() @@ -560,8 +558,6 @@ struct DSoundCapture final : public BackendBase { DWORD mCursor{0u}; RingBufferPtr mRing; - - DEF_NEWDEL(DSoundCapture) }; DSoundCapture::~DSoundCapture() diff --git a/alc/backends/jack.cpp b/alc/backends/jack.cpp index 1a53da17..eb87b0a7 100644 --- a/alc/backends/jack.cpp +++ b/alc/backends/jack.cpp @@ -319,8 +319,6 @@ struct JackPlayback final : public BackendBase { std::atomic mKillNow{true}; std::thread mThread; - - DEF_NEWDEL(JackPlayback) }; JackPlayback::~JackPlayback() diff --git a/alc/backends/loopback.cpp b/alc/backends/loopback.cpp index 2972fc01..e42e35b0 100644 --- a/alc/backends/loopback.cpp +++ b/alc/backends/loopback.cpp @@ -34,8 +34,6 @@ struct LoopbackBackend final : public BackendBase { bool reset() override; void start() override; void stop() override; - - DEF_NEWDEL(LoopbackBackend) }; diff --git a/alc/backends/null.cpp b/alc/backends/null.cpp index c149820c..f28eaa47 100644 --- a/alc/backends/null.cpp +++ b/alc/backends/null.cpp @@ -58,8 +58,6 @@ struct NullBackend final : public BackendBase { std::atomic mKillNow{true}; std::thread mThread; - - DEF_NEWDEL(NullBackend) }; int NullBackend::mixerProc() diff --git a/alc/backends/opensl.cpp b/alc/backends/opensl.cpp index 75b6e30d..6b2de909 100644 --- a/alc/backends/opensl.cpp +++ b/alc/backends/opensl.cpp @@ -190,8 +190,6 @@ struct OpenSLPlayback final : public BackendBase { std::atomic mKillNow{true}; std::thread mThread; - - DEF_NEWDEL(OpenSLPlayback) }; OpenSLPlayback::~OpenSLPlayback() @@ -595,8 +593,6 @@ struct OpenSLCapture final : public BackendBase { uint mSplOffset{0u}; uint mFrameSize{0}; - - DEF_NEWDEL(OpenSLCapture) }; OpenSLCapture::~OpenSLCapture() diff --git a/alc/backends/oss.cpp b/alc/backends/oss.cpp index e6cebec4..8e547497 100644 --- a/alc/backends/oss.cpp +++ b/alc/backends/oss.cpp @@ -240,8 +240,6 @@ struct OSSPlayback final : public BackendBase { std::atomic mKillNow{true}; std::thread mThread; - - DEF_NEWDEL(OSSPlayback) }; OSSPlayback::~OSSPlayback() @@ -457,8 +455,6 @@ struct OSScapture final : public BackendBase { std::atomic mKillNow{true}; std::thread mThread; - - DEF_NEWDEL(OSScapture) }; OSScapture::~OSScapture() diff --git a/alc/backends/pipewire.cpp b/alc/backends/pipewire.cpp index 2c726cbe..9c9323ec 100644 --- a/alc/backends/pipewire.cpp +++ b/alc/backends/pipewire.cpp @@ -1442,8 +1442,6 @@ public: /* Stop the mainloop so the stream can be properly destroyed. */ if(mLoop) mLoop.stop(); } - - DEF_NEWDEL(PipeWirePlayback) }; @@ -1927,8 +1925,6 @@ class PipeWireCapture final : public BackendBase { public: PipeWireCapture(DeviceBase *device) noexcept : BackendBase{device} { } ~PipeWireCapture() final { if(mLoop) mLoop.stop(); } - - DEF_NEWDEL(PipeWireCapture) }; diff --git a/alc/backends/portaudio.cpp b/alc/backends/portaudio.cpp index 554efe9a..dc9725b0 100644 --- a/alc/backends/portaudio.cpp +++ b/alc/backends/portaudio.cpp @@ -95,8 +95,6 @@ struct PortPlayback final : public BackendBase { PaStream *mStream{nullptr}; PaStreamParameters mParams{}; uint mUpdateSize{0u}; - - DEF_NEWDEL(PortPlayback) }; PortPlayback::~PortPlayback() @@ -256,8 +254,6 @@ struct PortCapture final : public BackendBase { PaStreamParameters mParams; RingBufferPtr mRing{nullptr}; - - DEF_NEWDEL(PortCapture) }; PortCapture::~PortCapture() diff --git a/alc/backends/pulseaudio.cpp b/alc/backends/pulseaudio.cpp index b6f0f95d..8533cdb9 100644 --- a/alc/backends/pulseaudio.cpp +++ b/alc/backends/pulseaudio.cpp @@ -664,8 +664,6 @@ struct PulsePlayback final : public BackendBase { pa_stream *mStream{nullptr}; uint mFrameSize{0u}; - - DEF_NEWDEL(PulsePlayback) }; PulsePlayback::~PulsePlayback() @@ -1090,8 +1088,6 @@ struct PulseCapture final : public BackendBase { pa_sample_spec mSpec{}; pa_stream *mStream{nullptr}; - - DEF_NEWDEL(PulseCapture) }; PulseCapture::~PulseCapture() diff --git a/alc/backends/sdl2.cpp b/alc/backends/sdl2.cpp index d7f66d93..49b9713e 100644 --- a/alc/backends/sdl2.cpp +++ b/alc/backends/sdl2.cpp @@ -67,8 +67,6 @@ struct Sdl2Backend final : public BackendBase { DevFmtChannels mFmtChans{}; DevFmtType mFmtType{}; uint mUpdateSize{0u}; - - DEF_NEWDEL(Sdl2Backend) }; Sdl2Backend::~Sdl2Backend() diff --git a/alc/backends/sndio.cpp b/alc/backends/sndio.cpp index d05db2e8..8477ed1f 100644 --- a/alc/backends/sndio.cpp +++ b/alc/backends/sndio.cpp @@ -70,8 +70,6 @@ struct SndioPlayback final : public BackendBase { std::atomic mKillNow{true}; std::thread mThread; - - DEF_NEWDEL(SndioPlayback) }; SndioPlayback::~SndioPlayback() @@ -293,8 +291,6 @@ struct SndioCapture final : public BackendBase { std::atomic mKillNow{true}; std::thread mThread; - - DEF_NEWDEL(SndioCapture) }; SndioCapture::~SndioCapture() diff --git a/alc/backends/solaris.cpp b/alc/backends/solaris.cpp index 2c4a97fd..b29a8cea 100644 --- a/alc/backends/solaris.cpp +++ b/alc/backends/solaris.cpp @@ -75,8 +75,6 @@ struct SolarisBackend final : public BackendBase { std::atomic mKillNow{true}; std::thread mThread; - - DEF_NEWDEL(SolarisBackend) }; SolarisBackend::~SolarisBackend() diff --git a/alc/backends/wasapi.cpp b/alc/backends/wasapi.cpp index 3e9632e0..a164ed24 100644 --- a/alc/backends/wasapi.cpp +++ b/alc/backends/wasapi.cpp @@ -1086,8 +1086,6 @@ struct WasapiPlayback final : public BackendBase, WasapiProxy { std::atomic mKillNow{true}; std::thread mThread; - - DEF_NEWDEL(WasapiPlayback) }; WasapiPlayback::~WasapiPlayback() @@ -2123,8 +2121,6 @@ struct WasapiCapture final : public BackendBase, WasapiProxy { std::atomic mKillNow{true}; std::thread mThread; - - DEF_NEWDEL(WasapiCapture) }; WasapiCapture::~WasapiCapture() diff --git a/alc/backends/wave.cpp b/alc/backends/wave.cpp index f3261ed4..11794608 100644 --- a/alc/backends/wave.cpp +++ b/alc/backends/wave.cpp @@ -109,8 +109,6 @@ struct WaveBackend final : public BackendBase { std::atomic mKillNow{true}; std::thread mThread; - - DEF_NEWDEL(WaveBackend) }; WaveBackend::~WaveBackend() diff --git a/alc/backends/winmm.cpp b/alc/backends/winmm.cpp index 696f7f37..a3d647ec 100644 --- a/alc/backends/winmm.cpp +++ b/alc/backends/winmm.cpp @@ -151,8 +151,6 @@ struct WinMMPlayback final : public BackendBase { std::atomic mKillNow{true}; std::thread mThread; - - DEF_NEWDEL(WinMMPlayback) }; WinMMPlayback::~WinMMPlayback() @@ -389,8 +387,6 @@ struct WinMMCapture final : public BackendBase { std::atomic mKillNow{true}; std::thread mThread; - - DEF_NEWDEL(WinMMCapture) }; WinMMCapture::~WinMMCapture() diff --git a/alc/context.h b/alc/context.h index d923e46e..9f49ceac 100644 --- a/alc/context.h +++ b/alc/context.h @@ -230,8 +230,6 @@ public: /* Default effect that applies to sources that don't have an effect on send 0. */ static ALeffect sDefaultEffect; - DEF_NEWDEL(ALCcontext) - #ifdef ALSOFT_EAX public: bool hasEax() const noexcept { return mEaxIsInitialized; } diff --git a/alc/device.h b/alc/device.h index 66f37a7e..0f36304b 100644 --- a/alc/device.h +++ b/alc/device.h @@ -148,8 +148,6 @@ struct ALCdevice : public al::intrusive_ref, DeviceBase { template inline std::optional configValue(const char *block, const char *key) = delete; - - DEF_NEWDEL(ALCdevice) }; template<> diff --git a/alc/effects/autowah.cpp b/alc/effects/autowah.cpp index 6d66f99f..20c790b6 100644 --- a/alc/effects/autowah.cpp +++ b/alc/effects/autowah.cpp @@ -88,8 +88,6 @@ struct AutowahState final : public EffectState { const EffectTarget target) override; void process(const size_t samplesToDo, const al::span samplesIn, const al::span samplesOut) override; - - DEF_NEWDEL(AutowahState) }; void AutowahState::deviceUpdate(const DeviceBase*, const BufferStorage*) diff --git a/alc/effects/chorus.cpp b/alc/effects/chorus.cpp index 098b33a1..d3bcd394 100644 --- a/alc/effects/chorus.cpp +++ b/alc/effects/chorus.cpp @@ -84,8 +84,6 @@ struct ChorusState final : public EffectState { const EffectTarget target) override; void process(const size_t samplesToDo, const al::span samplesIn, const al::span samplesOut) override; - - DEF_NEWDEL(ChorusState) }; void ChorusState::deviceUpdate(const DeviceBase *Device, const BufferStorage*) diff --git a/alc/effects/compressor.cpp b/alc/effects/compressor.cpp index 47ef64e9..eb8605ce 100644 --- a/alc/effects/compressor.cpp +++ b/alc/effects/compressor.cpp @@ -82,8 +82,6 @@ struct CompressorState final : public EffectState { const EffectTarget target) override; void process(const size_t samplesToDo, const al::span samplesIn, const al::span samplesOut) override; - - DEF_NEWDEL(CompressorState) }; void CompressorState::deviceUpdate(const DeviceBase *device, const BufferStorage*) diff --git a/alc/effects/convolution.cpp b/alc/effects/convolution.cpp index 1fcb419c..f497ebce 100644 --- a/alc/effects/convolution.cpp +++ b/alc/effects/convolution.cpp @@ -233,8 +233,6 @@ struct ConvolutionState final : public EffectState { const EffectTarget target) override; void process(const size_t samplesToDo, const al::span samplesIn, const al::span samplesOut) override; - - DEF_NEWDEL(ConvolutionState) }; void ConvolutionState::NormalMix(const al::span samplesOut, diff --git a/alc/effects/dedicated.cpp b/alc/effects/dedicated.cpp index 1b8b3977..609776ad 100644 --- a/alc/effects/dedicated.cpp +++ b/alc/effects/dedicated.cpp @@ -56,8 +56,6 @@ struct DedicatedState final : public EffectState { const EffectTarget target) override; void process(const size_t samplesToDo, const al::span samplesIn, const al::span samplesOut) override; - - DEF_NEWDEL(DedicatedState) }; void DedicatedState::deviceUpdate(const DeviceBase*, const BufferStorage*) diff --git a/alc/effects/distortion.cpp b/alc/effects/distortion.cpp index 9ef9de25..5e8253e8 100644 --- a/alc/effects/distortion.cpp +++ b/alc/effects/distortion.cpp @@ -61,8 +61,6 @@ struct DistortionState final : public EffectState { const EffectTarget target) override; void process(const size_t samplesToDo, const al::span samplesIn, const al::span samplesOut) override; - - DEF_NEWDEL(DistortionState) }; void DistortionState::deviceUpdate(const DeviceBase*, const BufferStorage*) diff --git a/alc/effects/echo.cpp b/alc/effects/echo.cpp index fe6d8258..8def5e71 100644 --- a/alc/effects/echo.cpp +++ b/alc/effects/echo.cpp @@ -73,8 +73,6 @@ struct EchoState final : public EffectState { const EffectTarget target) override; void process(const size_t samplesToDo, const al::span samplesIn, const al::span samplesOut) override; - - DEF_NEWDEL(EchoState) }; void EchoState::deviceUpdate(const DeviceBase *Device, const BufferStorage*) diff --git a/alc/effects/equalizer.cpp b/alc/effects/equalizer.cpp index a4a1777a..9cb42470 100644 --- a/alc/effects/equalizer.cpp +++ b/alc/effects/equalizer.cpp @@ -106,8 +106,6 @@ struct EqualizerState final : public EffectState { const EffectTarget target) override; void process(const size_t samplesToDo, const al::span samplesIn, const al::span samplesOut) override; - - DEF_NEWDEL(EqualizerState) }; void EqualizerState::deviceUpdate(const DeviceBase*, const BufferStorage*) diff --git a/alc/effects/fshifter.cpp b/alc/effects/fshifter.cpp index d121885b..2add8379 100644 --- a/alc/effects/fshifter.cpp +++ b/alc/effects/fshifter.cpp @@ -103,8 +103,6 @@ struct FshifterState final : public EffectState { const EffectTarget target) override; void process(const size_t samplesToDo, const al::span samplesIn, const al::span samplesOut) override; - - DEF_NEWDEL(FshifterState) }; void FshifterState::deviceUpdate(const DeviceBase*, const BufferStorage*) diff --git a/alc/effects/modulator.cpp b/alc/effects/modulator.cpp index 3c612a6e..29c225e3 100644 --- a/alc/effects/modulator.cpp +++ b/alc/effects/modulator.cpp @@ -105,8 +105,6 @@ struct ModulatorState final : public EffectState { const EffectTarget target) override; void process(const size_t samplesToDo, const al::span samplesIn, const al::span samplesOut) override; - - DEF_NEWDEL(ModulatorState) }; template<> diff --git a/alc/effects/null.cpp b/alc/effects/null.cpp index 12d1688e..964afe47 100644 --- a/alc/effects/null.cpp +++ b/alc/effects/null.cpp @@ -25,8 +25,6 @@ struct NullState final : public EffectState { const EffectTarget target) override; void process(const size_t samplesToDo, const al::span samplesIn, const al::span samplesOut) override; - - DEF_NEWDEL(NullState) }; /* This constructs the effect state. It's called when the object is first diff --git a/alc/effects/pshifter.cpp b/alc/effects/pshifter.cpp index c7d662c7..24171082 100644 --- a/alc/effects/pshifter.cpp +++ b/alc/effects/pshifter.cpp @@ -112,8 +112,6 @@ struct PshifterState final : public EffectState { const EffectTarget target) override; void process(const size_t samplesToDo, const al::span samplesIn, const al::span samplesOut) override; - - DEF_NEWDEL(PshifterState) }; void PshifterState::deviceUpdate(const DeviceBase*, const BufferStorage*) diff --git a/alc/effects/reverb.cpp b/alc/effects/reverb.cpp index 43451ec8..4318fa28 100644 --- a/alc/effects/reverb.cpp +++ b/alc/effects/reverb.cpp @@ -662,8 +662,6 @@ struct ReverbState final : public EffectState { const EffectTarget target) override; void process(const size_t samplesToDo, const al::span samplesIn, const al::span samplesOut) override; - - DEF_NEWDEL(ReverbState) }; /************************************** diff --git a/alc/effects/vmorpher.cpp b/alc/effects/vmorpher.cpp index 6cf862c2..adbcdeab 100644 --- a/alc/effects/vmorpher.cpp +++ b/alc/effects/vmorpher.cpp @@ -173,8 +173,6 @@ struct VmorpherState final : public EffectState { static std::array getFiltersByPhoneme(VMorpherPhenome phoneme, float frequency, float pitch) noexcept; - - DEF_NEWDEL(VmorpherState) }; std::array VmorpherState::getFiltersByPhoneme(VMorpherPhenome phoneme, diff --git a/common/almalloc.h b/common/almalloc.h index b3d8dd58..7ac02bf1 100644 --- a/common/almalloc.h +++ b/common/almalloc.h @@ -26,19 +26,6 @@ void *al_calloc(size_t alignment, size_t size); void operator delete(void*) noexcept = delete; \ void operator delete[](void*) noexcept = delete; -#define DEF_NEWDEL(T) \ - void *operator new(size_t size) \ - { \ - static_assert(&operator new == &T::operator new, \ - "Incorrect container type specified"); \ - if(void *ret{al_malloc(alignof(T), size)}) \ - return ret; \ - throw std::bad_alloc(); \ - } \ - void *operator new[](size_t size) { return operator new(size); } \ - void operator delete(void *block) noexcept { al_free(block); } \ - void operator delete[](void *block) noexcept { operator delete(block); } - #define DEF_PLACE_NEWDEL \ void *operator new(size_t) = delete; \ void *operator new[](size_t) = delete; \ diff --git a/core/bformatdec.h b/core/bformatdec.h index 97e7c9e4..35cf20a2 100644 --- a/core/bformatdec.h +++ b/core/bformatdec.h @@ -58,8 +58,6 @@ public: static std::unique_ptr Create(const size_t inchans, const al::span coeffs, const al::span coeffslf, const float xover_f0norm, std::unique_ptr stablizer); - - DEF_NEWDEL(BFormatDec) }; #endif /* CORE_BFORMATDEC_H */ diff --git a/core/context.h b/core/context.h index 15897ff3..0b830205 100644 --- a/core/context.h +++ b/core/context.h @@ -27,9 +27,9 @@ struct VoiceChange; struct VoicePropsItem; -constexpr float SpeedOfSoundMetersPerSec{343.3f}; +inline constexpr float SpeedOfSoundMetersPerSec{343.3f}; -constexpr float AirAbsorbGainHF{0.99426f}; /* -0.05dB */ +inline constexpr float AirAbsorbGainHF{0.99426f}; /* -0.05dB */ enum class DistanceModel : unsigned char { Disable, @@ -57,8 +57,6 @@ struct ContextProps { DistanceModel mDistanceModel; std::atomic next; - - DEF_NEWDEL(ContextProps) }; struct ContextParams { diff --git a/core/device.h b/core/device.h index 93d64aef..d85b9254 100644 --- a/core/device.h +++ b/core/device.h @@ -380,8 +380,6 @@ struct DeviceBase { [[nodiscard]] auto channelIdxByName(Channel chan) const noexcept -> uint8_t { return RealOut.ChannelIndex[chan]; } - DISABLE_ALLOC - private: uint renderSamples(const uint numSamples); }; diff --git a/core/effectslot.h b/core/effectslot.h index 3362ba85..cf8503ff 100644 --- a/core/effectslot.h +++ b/core/effectslot.h @@ -46,8 +46,6 @@ struct EffectSlotProps { al::intrusive_ptr State; std::atomic next; - - DEF_NEWDEL(EffectSlotProps) }; @@ -83,8 +81,6 @@ struct EffectSlot { static EffectSlotArray *CreatePtrArray(size_t count) noexcept; - - DEF_NEWDEL(EffectSlot) }; #endif /* CORE_EFFECTSLOT_H */ diff --git a/core/uhjfilter.h b/core/uhjfilter.h index 29838410..58576beb 100644 --- a/core/uhjfilter.h +++ b/core/uhjfilter.h @@ -110,8 +110,6 @@ struct UhjEncoderIIR final : public UhjEncoderBase { */ void encode(float *LeftOut, float *RightOut, const al::span InSamples, const size_t SamplesToDo) override; - - DEF_NEWDEL(UhjEncoderIIR) }; @@ -158,8 +156,6 @@ struct UhjDecoder final : public DecoderBase { */ void decode(const al::span samples, const size_t samplesToDo, const bool updateState) override; - - DEF_NEWDEL(UhjDecoder) }; struct UhjDecoderIIR final : public DecoderBase { @@ -184,8 +180,6 @@ struct UhjDecoderIIR final : public DecoderBase { void decode(const al::span samples, const size_t samplesToDo, const bool updateState) override; - - DEF_NEWDEL(UhjDecoderIIR) }; template @@ -210,8 +204,6 @@ struct UhjStereoDecoder final : public DecoderBase { */ void decode(const al::span samples, const size_t samplesToDo, const bool updateState) override; - - DEF_NEWDEL(UhjStereoDecoder) }; struct UhjStereoDecoderIIR final : public DecoderBase { @@ -231,8 +223,6 @@ struct UhjStereoDecoderIIR final : public DecoderBase { void decode(const al::span samples, const size_t samplesToDo, const bool updateState) override; - - DEF_NEWDEL(UhjStereoDecoderIIR) }; #endif /* CORE_UHJFILTER_H */ diff --git a/core/voice.h b/core/voice.h index 6c953804..2ecc8148 100644 --- a/core/voice.h +++ b/core/voice.h @@ -160,8 +160,6 @@ struct VoiceProps { struct VoicePropsItem : public VoiceProps { std::atomic next{nullptr}; - - DEF_NEWDEL(VoicePropsItem) }; enum : uint { @@ -271,8 +269,6 @@ struct Voice { void prepare(DeviceBase *device); static void InitMixer(std::optional resampler); - - DEF_NEWDEL(Voice) }; extern Resampler ResamplerDefault; diff --git a/core/voice_change.h b/core/voice_change.h index ddc6186f..e97c48f3 100644 --- a/core/voice_change.h +++ b/core/voice_change.h @@ -3,8 +3,6 @@ #include -#include "almalloc.h" - struct Voice; using uint = unsigned int; @@ -24,8 +22,6 @@ struct VoiceChange { VChangeState mState{}; std::atomic mNext{nullptr}; - - DEF_NEWDEL(VoiceChange) }; #endif /* VOICE_CHANGE_H */ diff --git a/utils/uhjdecoder.cpp b/utils/uhjdecoder.cpp index feca0a35..801425e0 100644 --- a/utils/uhjdecoder.cpp +++ b/utils/uhjdecoder.cpp @@ -35,7 +35,6 @@ #include "albit.h" #include "alcomplex.h" -#include "almalloc.h" #include "alnumbers.h" #include "alspan.h" #include "vector.h" @@ -129,8 +128,6 @@ struct UhjDecoder { const al::span OutSamples, const std::size_t SamplesToDo); void decode2(const float *RESTRICT InSamples, const al::span OutSamples, const std::size_t SamplesToDo); - - DEF_NEWDEL(UhjDecoder) }; const PhaseShifterT PShift{}; diff --git a/utils/uhjencoder.cpp b/utils/uhjencoder.cpp index 8673dd59..6a7b1fa9 100644 --- a/utils/uhjencoder.cpp +++ b/utils/uhjencoder.cpp @@ -33,7 +33,6 @@ #include #include -#include "almalloc.h" #include "alnumbers.h" #include "alspan.h" #include "opthelpers.h" @@ -82,8 +81,6 @@ struct UhjEncoder { void encode(const al::span OutSamples, const al::span InSamples, const size_t SamplesToDo); - - DEF_NEWDEL(UhjEncoder) }; const PhaseShifterT PShift{}; -- cgit v1.2.3 From aa6e04a5562052db172117043165ae999683b052 Mon Sep 17 00:00:00 2001 From: Chris Robinson Date: Wed, 20 Dec 2023 01:53:27 -0800 Subject: Ensure struct members are initialized --- al/source.h | 22 +++++++++---------- alc/backends/portaudio.cpp | 34 +++++++++++++++--------------- alc/backends/pulseaudio.cpp | 4 ++-- alc/backends/sndio.cpp | 2 +- alc/effects/autowah.cpp | 26 +++++++++++------------ alc/effects/chorus.cpp | 4 ++-- alc/effects/dedicated.cpp | 4 ++-- alc/effects/echo.cpp | 2 +- alc/effects/fshifter.cpp | 2 +- alc/effects/pshifter.cpp | 32 ++++++++++++++-------------- alc/effects/reverb.cpp | 6 +++--- common/alsem.h | 2 +- common/polyphase_resampler.h | 2 +- core/bformatdec.h | 6 +++--- core/device.h | 10 ++++----- core/filters/nfc.h | 24 ++++++++++----------- core/hrtf.h | 2 +- core/uhjfilter.h | 2 +- core/voice.h | 50 ++++++++++++++++++++++---------------------- examples/alffplay.cpp | 2 +- examples/alstreamcb.cpp | 2 +- utils/makemhr/makemhr.cpp | 8 +++---- 22 files changed, 124 insertions(+), 124 deletions(-) (limited to 'alc/backends/pulseaudio.cpp') diff --git a/al/source.h b/al/source.h index 69bedda3..1a93d927 100644 --- a/al/source.h +++ b/al/source.h @@ -108,19 +108,19 @@ struct ALsource { /** Direct filter and auxiliary send info. */ struct { - float Gain; - float GainHF; - float HFReference; - float GainLF; - float LFReference; + float Gain{}; + float GainHF{}; + float HFReference{}; + float GainLF{}; + float LFReference{}; } Direct; struct SendData { - ALeffectslot *Slot; - float Gain; - float GainHF; - float HFReference; - float GainLF; - float LFReference; + ALeffectslot *Slot{}; + float Gain{}; + float GainHF{}; + float HFReference{}; + float GainLF{}; + float LFReference{}; }; std::array Send; diff --git a/alc/backends/portaudio.cpp b/alc/backends/portaudio.cpp index dc9725b0..b6013dcc 100644 --- a/alc/backends/portaudio.cpp +++ b/alc/backends/portaudio.cpp @@ -79,13 +79,6 @@ struct PortPlayback final : public BackendBase { int writeCallback(const void *inputBuffer, void *outputBuffer, unsigned long framesPerBuffer, const PaStreamCallbackTimeInfo *timeInfo, const PaStreamCallbackFlags statusFlags) noexcept; - static int writeCallbackC(const void *inputBuffer, void *outputBuffer, - unsigned long framesPerBuffer, const PaStreamCallbackTimeInfo *timeInfo, - const PaStreamCallbackFlags statusFlags, void *userData) noexcept - { - return static_cast(userData)->writeCallback(inputBuffer, outputBuffer, - framesPerBuffer, timeInfo, statusFlags); - } void open(std::string_view name) override; bool reset() override; @@ -156,9 +149,16 @@ void PortPlayback::open(std::string_view name) } retry_open: + static constexpr auto writeCallback = [](const void *inputBuffer, void *outputBuffer, + unsigned long framesPerBuffer, const PaStreamCallbackTimeInfo *timeInfo, + const PaStreamCallbackFlags statusFlags, void *userData) noexcept + { + return static_cast(userData)->writeCallback(inputBuffer, outputBuffer, + framesPerBuffer, timeInfo, statusFlags); + }; PaStream *stream{}; PaError err{Pa_OpenStream(&stream, nullptr, ¶ms, mDevice->Frequency, mDevice->UpdateSize, - paNoFlag, &PortPlayback::writeCallbackC, this)}; + paNoFlag, writeCallback, this)}; if(err != paNoError) { if(params.sampleFormat == paFloat32) @@ -236,13 +236,6 @@ struct PortCapture final : public BackendBase { int readCallback(const void *inputBuffer, void *outputBuffer, unsigned long framesPerBuffer, const PaStreamCallbackTimeInfo *timeInfo, const PaStreamCallbackFlags statusFlags) noexcept; - static int readCallbackC(const void *inputBuffer, void *outputBuffer, - unsigned long framesPerBuffer, const PaStreamCallbackTimeInfo *timeInfo, - const PaStreamCallbackFlags statusFlags, void *userData) noexcept - { - return static_cast(userData)->readCallback(inputBuffer, outputBuffer, - framesPerBuffer, timeInfo, statusFlags); - } void open(std::string_view name) override; void start() override; @@ -251,7 +244,7 @@ struct PortCapture final : public BackendBase { uint availableSamples() override; PaStream *mStream{nullptr}; - PaStreamParameters mParams; + PaStreamParameters mParams{}; RingBufferPtr mRing{nullptr}; }; @@ -317,8 +310,15 @@ void PortCapture::open(std::string_view name) } mParams.channelCount = static_cast(mDevice->channelsFromFmt()); + static constexpr auto readCallback = [](const void *inputBuffer, void *outputBuffer, + unsigned long framesPerBuffer, const PaStreamCallbackTimeInfo *timeInfo, + const PaStreamCallbackFlags statusFlags, void *userData) noexcept + { + return static_cast(userData)->readCallback(inputBuffer, outputBuffer, + framesPerBuffer, timeInfo, statusFlags); + }; PaError err{Pa_OpenStream(&mStream, &mParams, nullptr, mDevice->Frequency, - paFramesPerBufferUnspecified, paNoFlag, &PortCapture::readCallbackC, this)}; + paFramesPerBufferUnspecified, paNoFlag, readCallback, this)}; if(err != paNoError) throw al::backend_exception{al::backend_error::NoDevice, "Failed to open stream: %s", Pa_GetErrorText(err)}; diff --git a/alc/backends/pulseaudio.cpp b/alc/backends/pulseaudio.cpp index 8533cdb9..aec91229 100644 --- a/alc/backends/pulseaudio.cpp +++ b/alc/backends/pulseaudio.cpp @@ -658,8 +658,8 @@ struct PulsePlayback final : public BackendBase { std::optional mDeviceName{std::nullopt}; bool mIs51Rear{false}; - pa_buffer_attr mAttr; - pa_sample_spec mSpec; + pa_buffer_attr mAttr{}; + pa_sample_spec mSpec{}; pa_stream *mStream{nullptr}; diff --git a/alc/backends/sndio.cpp b/alc/backends/sndio.cpp index 8477ed1f..2cb577fd 100644 --- a/alc/backends/sndio.cpp +++ b/alc/backends/sndio.cpp @@ -47,7 +47,7 @@ namespace { constexpr char sndio_device[] = "SndIO Default"; struct SioPar : public sio_par { - SioPar() { sio_initpar(this); } + SioPar() : sio_par{} { sio_initpar(this); } void clear() { sio_initpar(this); } }; diff --git a/alc/effects/autowah.cpp b/alc/effects/autowah.cpp index 20c790b6..e9e14e35 100644 --- a/alc/effects/autowah.cpp +++ b/alc/effects/autowah.cpp @@ -50,18 +50,18 @@ constexpr float QFactor{5.0f}; struct AutowahState final : public EffectState { /* Effect parameters */ - float mAttackRate; - float mReleaseRate; - float mResonanceGain; - float mPeakGain; - float mFreqMinNorm; - float mBandwidthNorm; - float mEnvDelay; + float mAttackRate{}; + float mReleaseRate{}; + float mResonanceGain{}; + float mPeakGain{}; + float mFreqMinNorm{}; + float mBandwidthNorm{}; + float mEnvDelay{}; /* Filter components derived from the envelope. */ struct FilterParam { - float cos_w0; - float alpha; + float cos_w0{}; + float alpha{}; }; std::array mEnv; @@ -70,17 +70,17 @@ struct AutowahState final : public EffectState { /* Effect filters' history. */ struct { - float z1, z2; + float z1{}, z2{}; } mFilter; /* Effect gains for each output channel */ - float mCurrentGain; - float mTargetGain; + float mCurrentGain{}; + float mTargetGain{}; }; std::array mChans; /* Effects buffers */ - alignas(16) FloatBufferLine mBufferOut; + alignas(16) FloatBufferLine mBufferOut{}; void deviceUpdate(const DeviceBase *device, const BufferStorage *buffer) override; diff --git a/alc/effects/chorus.cpp b/alc/effects/chorus.cpp index d3bcd394..f56c9f2c 100644 --- a/alc/effects/chorus.cpp +++ b/alc/effects/chorus.cpp @@ -58,10 +58,10 @@ struct ChorusState final : public EffectState { uint mLfoDisp{0}; /* Calculated delays to apply to the left and right outputs. */ - std::array,2> mModDelays; + std::array,2> mModDelays{}; /* Temp storage for the modulated left and right outputs. */ - alignas(16) std::array mBuffer; + alignas(16) std::array mBuffer{}; /* Gains for left and right outputs. */ struct OutGains { diff --git a/alc/effects/dedicated.cpp b/alc/effects/dedicated.cpp index 609776ad..a3d4298d 100644 --- a/alc/effects/dedicated.cpp +++ b/alc/effects/dedicated.cpp @@ -47,8 +47,8 @@ struct DedicatedState final : public EffectState { * gains for all possible output channels and not just the main ambisonic * buffer. */ - std::array mCurrentGains; - std::array mTargetGains; + std::array mCurrentGains{}; + std::array mTargetGains{}; void deviceUpdate(const DeviceBase *device, const BufferStorage *buffer) override; diff --git a/alc/effects/echo.cpp b/alc/effects/echo.cpp index 8def5e71..2f3343e8 100644 --- a/alc/effects/echo.cpp +++ b/alc/effects/echo.cpp @@ -66,7 +66,7 @@ struct EchoState final : public EffectState { BiquadFilter mFilter; float mFeedGain{0.0f}; - alignas(16) std::array mTempBuffer; + alignas(16) std::array mTempBuffer{}; void deviceUpdate(const DeviceBase *device, const BufferStorage *buffer) override; void update(const ContextBase *context, const EffectSlot *slot, const EffectProps *props, diff --git a/alc/effects/fshifter.cpp b/alc/effects/fshifter.cpp index 2add8379..433ebfe4 100644 --- a/alc/effects/fshifter.cpp +++ b/alc/effects/fshifter.cpp @@ -57,7 +57,7 @@ constexpr size_t HilStep{HilSize / OversampleFactor}; /* Define a Hann window, used to filter the HIL input and output. */ struct Windower { - alignas(16) std::array mData; + alignas(16) std::array mData{}; Windower() { diff --git a/alc/effects/pshifter.cpp b/alc/effects/pshifter.cpp index 24171082..9714510f 100644 --- a/alc/effects/pshifter.cpp +++ b/alc/effects/pshifter.cpp @@ -58,7 +58,7 @@ constexpr size_t StftStep{StftSize / OversampleFactor}; /* Define a Hann window, used to filter the STFT input and output. */ struct Windower { - alignas(16) std::array mData; + alignas(16) std::array mData{}; Windower() { @@ -82,29 +82,29 @@ struct FrequencyBin { struct PshifterState final : public EffectState { /* Effect parameters */ - size_t mCount; - size_t mPos; - uint mPitchShiftI; - float mPitchShift; + size_t mCount{}; + size_t mPos{}; + uint mPitchShiftI{}; + float mPitchShift{}; /* Effects buffers */ - std::array mFIFO; - std::array mLastPhase; - std::array mSumPhase; - std::array mOutputAccum; + std::array mFIFO{}; + std::array mLastPhase{}; + std::array mSumPhase{}; + std::array mOutputAccum{}; PFFFTSetup mFft; - alignas(16) std::array mFftBuffer; - alignas(16) std::array mFftWorkBuffer; + alignas(16) std::array mFftBuffer{}; + alignas(16) std::array mFftWorkBuffer{}; - std::array mAnalysisBuffer; - std::array mSynthesisBuffer; + std::array mAnalysisBuffer{}; + std::array mSynthesisBuffer{}; - alignas(16) FloatBufferLine mBufferOut; + alignas(16) FloatBufferLine mBufferOut{}; /* Effect gains for each output channel */ - std::array mCurrentGains; - std::array mTargetGains; + std::array mCurrentGains{}; + std::array mTargetGains{}; void deviceUpdate(const DeviceBase *device, const BufferStorage *buffer) override; diff --git a/alc/effects/reverb.cpp b/alc/effects/reverb.cpp index 4318fa28..cc5768e2 100644 --- a/alc/effects/reverb.cpp +++ b/alc/effects/reverb.cpp @@ -417,12 +417,12 @@ struct Modulation { /* The vibrato time is tracked with an index over a (MOD_FRACONE) * normalized range. */ - uint Index, Step; + uint Index{}, Step{}; /* The depth of frequency change, in samples. */ - float Depth; + float Depth{}; - std::array ModDelays; + std::array ModDelays{}; void updateModulator(float modTime, float modDepth, float frequency); diff --git a/common/alsem.h b/common/alsem.h index 9f72d1c6..90b39319 100644 --- a/common/alsem.h +++ b/common/alsem.h @@ -24,7 +24,7 @@ class semaphore { #else using native_type = sem_t; #endif - native_type mSem; + native_type mSem{}; public: semaphore(unsigned int initial=0); diff --git a/common/polyphase_resampler.h b/common/polyphase_resampler.h index 557485bb..764111c9 100644 --- a/common/polyphase_resampler.h +++ b/common/polyphase_resampler.h @@ -40,7 +40,7 @@ struct PPhaseResampler { explicit operator bool() const noexcept { return !mF.empty(); } private: - uint mP, mQ, mM, mL; + uint mP{}, mQ{}, mM{}, mL{}; std::vector mF; }; diff --git a/core/bformatdec.h b/core/bformatdec.h index 35cf20a2..8513db03 100644 --- a/core/bformatdec.h +++ b/core/bformatdec.h @@ -25,15 +25,15 @@ class BFormatDec { static constexpr size_t sNumBands{2}; struct ChannelDecoderSingle { - std::array mGains; + std::array mGains{}; }; struct ChannelDecoderDual { BandSplitter mXOver; - std::array,sNumBands> mGains; + std::array,sNumBands> mGains{}; }; - alignas(16) std::array mSamples; + alignas(16) std::array mSamples{}; const std::unique_ptr mStablizer; diff --git a/core/device.h b/core/device.h index d85b9254..f02700c6 100644 --- a/core/device.h +++ b/core/device.h @@ -237,17 +237,17 @@ struct DeviceBase { static constexpr size_t MixerLineSize{BufferLineSize + DecoderBase::sMaxPadding}; static constexpr size_t MixerChannelsMax{16}; using MixerBufferLine = std::array; - alignas(16) std::array mSampleData; - alignas(16) std::array mResampleData; + alignas(16) std::array mSampleData{}; + alignas(16) std::array mResampleData{}; - alignas(16) std::array FilteredData; + alignas(16) std::array FilteredData{}; union { - alignas(16) std::array HrtfSourceData; + alignas(16) std::array HrtfSourceData{}; alignas(16) std::array NfcSampleData; }; /* Persistent storage for HRTF mixing. */ - alignas(16) std::array HrtfAccumData; + alignas(16) std::array HrtfAccumData{}; /* Mixing buffer used by the Dry mix and Real output. */ al::vector MixBuffer; diff --git a/core/filters/nfc.h b/core/filters/nfc.h index 7d0a7488..9c58f863 100644 --- a/core/filters/nfc.h +++ b/core/filters/nfc.h @@ -8,24 +8,24 @@ struct NfcFilter1 { - float base_gain, gain; - float b1, a1; - std::array z; + float base_gain{1.0f}, gain{1.0f}; + float b1{}, a1{}; + std::array z{}; }; struct NfcFilter2 { - float base_gain, gain; - float b1, b2, a1, a2; - std::array z; + float base_gain{1.0f}, gain{1.0f}; + float b1{}, b2{}, a1{}, a2{}; + std::array z{}; }; struct NfcFilter3 { - float base_gain, gain; - float b1, b2, b3, a1, a2, a3; - std::array z; + float base_gain{1.0f}, gain{1.0f}; + float b1{}, b2{}, b3{}, a1{}, a2{}, a3{}; + std::array z{}; }; struct NfcFilter4 { - float base_gain, gain; - float b1, b2, b3, b4, a1, a2, a3, a4; - std::array z; + float base_gain{1.0f}, gain{1.0f}; + float b1{}, b2{}, b3{}, b4{}, a1{}, a2{}, a3{}, a4{}; + std::array z{}; }; class NfcFilter { diff --git a/core/hrtf.h b/core/hrtf.h index e0263493..7a1a8b69 100644 --- a/core/hrtf.h +++ b/core/hrtf.h @@ -61,7 +61,7 @@ struct AngularPoint { struct DirectHrtfState { - std::array mTemp; + std::array mTemp{}; /* HRTF filter state for dry buffer content */ uint mIrSize{0}; diff --git a/core/uhjfilter.h b/core/uhjfilter.h index 58576beb..74ff2167 100644 --- a/core/uhjfilter.h +++ b/core/uhjfilter.h @@ -25,7 +25,7 @@ extern UhjQualityType UhjEncodeQuality; struct UhjAllPassFilter { struct AllPassState { /* Last two delayed components for direct form II. */ - std::array z; + std::array z{}; }; std::array mState; diff --git a/core/voice.h b/core/voice.h index 2ecc8148..aaf1c5fd 100644 --- a/core/voice.h +++ b/core/voice.h @@ -66,14 +66,14 @@ struct DirectParams { NfcFilter NFCtrlFilter; struct { - HrtfFilter Old; - HrtfFilter Target; - alignas(16) std::array History; + HrtfFilter Old{}; + HrtfFilter Target{}; + alignas(16) std::array History{}; } Hrtf; struct { - std::array Current; - std::array Target; + std::array Current{}; + std::array Target{}; } Gains; }; @@ -82,8 +82,8 @@ struct SendParams { BiquadFilter HighPass; struct { - std::array Current; - std::array Target; + std::array Current{}; + std::array Target{}; } Gains; }; @@ -184,7 +184,7 @@ struct Voice { std::atomic mUpdate{nullptr}; - VoiceProps mProps; + VoiceProps mProps{}; std::atomic mSourceID{0u}; std::atomic mPlayState{Stopped}; @@ -194,30 +194,30 @@ struct Voice { * Source offset in samples, relative to the currently playing buffer, NOT * the whole queue. */ - std::atomic mPosition; + std::atomic mPosition{}; /** Fractional (fixed-point) offset to the next sample. */ - std::atomic mPositionFrac; + std::atomic mPositionFrac{}; /* Current buffer queue item being played. */ - std::atomic mCurrentBuffer; + std::atomic mCurrentBuffer{}; /* Buffer queue item to loop to at end of queue (will be NULL for non- * looping voices). */ - std::atomic mLoopBuffer; + std::atomic mLoopBuffer{}; std::chrono::nanoseconds mStartTime{}; /* Properties for the attached buffer(s). */ - FmtChannels mFmtChannels; - FmtType mFmtType; - uint mFrequency; - uint mFrameStep; /**< In steps of the sample type size. */ - uint mBytesPerBlock; /**< Or for PCM formats, BytesPerFrame. */ - uint mSamplesPerBlock; /**< Always 1 for PCM formats. */ - AmbiLayout mAmbiLayout; - AmbiScaling mAmbiScaling; - uint mAmbiOrder; + FmtChannels mFmtChannels{}; + FmtType mFmtType{}; + uint mFrequency{}; + uint mFrameStep{}; /**< In steps of the sample type size. */ + uint mBytesPerBlock{}; /**< Or for PCM formats, BytesPerFrame. */ + uint mSamplesPerBlock{}; /**< Always 1 for PCM formats. */ + AmbiLayout mAmbiLayout{}; + AmbiScaling mAmbiScaling{}; + uint mAmbiOrder{}; std::unique_ptr mDecoder; uint mDecoderPadding{}; @@ -225,16 +225,16 @@ struct Voice { /** Current target parameters used for mixing. */ uint mStep{0}; - ResamplerFunc mResampler; + ResamplerFunc mResampler{}; - InterpState mResampleState; + InterpState mResampleState{}; std::bitset mFlags{}; uint mNumCallbackBlocks{0}; uint mCallbackBlockBase{0}; struct TargetData { - int FilterType; + int FilterType{}; al::span Buffer; }; TargetData mDirect; @@ -249,7 +249,7 @@ struct Voice { al::vector mPrevSamples{2}; struct ChannelData { - float mAmbiHFScale, mAmbiLFScale; + float mAmbiHFScale{}, mAmbiLFScale{}; BandSplitter mAmbiSplitter; DirectParams mDryParams; diff --git a/examples/alffplay.cpp b/examples/alffplay.cpp index 347d0b14..7a4b7aac 100644 --- a/examples/alffplay.cpp +++ b/examples/alffplay.cpp @@ -322,7 +322,7 @@ struct AudioState { std::mutex mSrcMutex; std::condition_variable mSrcCond; - std::atomic_flag mConnected; + std::atomic_flag mConnected{}; ALuint mSource{0}; std::array mBuffers{}; ALuint mBufferIdx{0}; diff --git a/examples/alstreamcb.cpp b/examples/alstreamcb.cpp index 95f89bbe..1721d367 100644 --- a/examples/alstreamcb.cpp +++ b/examples/alstreamcb.cpp @@ -79,7 +79,7 @@ struct StreamPlayer { size_t mDecoderOffset{0}; /* The format of the callback samples. */ - ALenum mFormat; + ALenum mFormat{}; StreamPlayer() { diff --git a/utils/makemhr/makemhr.cpp b/utils/makemhr/makemhr.cpp index 80e217ee..014b2967 100644 --- a/utils/makemhr/makemhr.cpp +++ b/utils/makemhr/makemhr.cpp @@ -871,10 +871,10 @@ static void SynthesizeHrirs(HrirDataT *hData) */ struct HrirReconstructor { std::vector mIrs; - std::atomic mCurrent; - std::atomic mDone; - uint mFftSize; - uint mIrPoints; + std::atomic mCurrent{}; + std::atomic mDone{}; + uint mFftSize{}; + uint mIrPoints{}; void Worker() { -- cgit v1.2.3 From 863c48a3e78e8a2f1e9217eaf6cda02cbe44e366 Mon Sep 17 00:00:00 2001 From: Chris Robinson Date: Thu, 21 Dec 2023 21:26:36 -0800 Subject: Use string_views for querying config parameters --- al/error.cpp | 2 +- alc/alc.cpp | 62 ++++++++++++++++++++++----------------------- alc/alconfig.cpp | 35 +++++++++++++++---------- alc/alconfig.h | 19 +++++++++----- alc/backends/alsa.cpp | 29 ++++++++++----------- alc/backends/jack.cpp | 10 ++++---- alc/backends/oss.cpp | 4 +-- alc/backends/pipewire.cpp | 4 +-- alc/backends/portaudio.cpp | 4 +-- alc/backends/pulseaudio.cpp | 12 ++++----- alc/backends/solaris.cpp | 2 +- alc/backends/wasapi.cpp | 6 ++--- alc/backends/wave.cpp | 4 +-- alc/device.cpp | 4 +-- alc/device.h | 26 +++++++++---------- alc/panning.cpp | 8 +++--- 16 files changed, 122 insertions(+), 109 deletions(-) (limited to 'alc/backends/pulseaudio.cpp') diff --git a/al/error.cpp b/al/error.cpp index b8692118..26dc522f 100644 --- a/al/error.cpp +++ b/al/error.cpp @@ -108,7 +108,7 @@ AL_API auto AL_APIENTRY alGetError() noexcept -> ALenum { auto optstr = al::getenv(envname); if(!optstr) - optstr = ConfigValueStr(nullptr, "game_compat", optname); + optstr = ConfigValueStr({}, "game_compat", optname); if(optstr) { diff --git a/alc/alc.cpp b/alc/alc.cpp index a0fbdb0f..3ad07aaa 100644 --- a/alc/alc.cpp +++ b/alc/alc.cpp @@ -427,7 +427,7 @@ void alc_initconfig() #ifdef HAVE_NEON capfilter |= CPU_CAP_NEON; #endif - if(auto cpuopt = ConfigValueStr(nullptr, nullptr, "disable-cpu-exts")) + if(auto cpuopt = ConfigValueStr({}, {}, "disable-cpu-exts")) { const char *str{cpuopt->c_str()}; if(al::strcasecmp(str, "all") == 0) @@ -480,9 +480,9 @@ void alc_initconfig() CPUCapFlags = caps & capfilter; } - if(auto priopt = ConfigValueInt(nullptr, nullptr, "rt-prio")) + if(auto priopt = ConfigValueInt({}, {}, "rt-prio")) RTPrioLevel = *priopt; - if(auto limopt = ConfigValueBool(nullptr, nullptr, "rt-time-limit")) + if(auto limopt = ConfigValueBool({}, {}, "rt-time-limit")) AllowRTTimeLimit = *limopt; { @@ -496,18 +496,18 @@ void alc_initconfig() return true; return false; } - return GetConfigValueBool(nullptr, "game_compat", optname, false); + return GetConfigValueBool({}, "game_compat", optname, false); }; sBufferSubDataCompat = checkflag("__ALSOFT_ENABLE_SUB_DATA_EXT", "enable-sub-data-ext"); compatflags.set(CompatFlags::ReverseX, checkflag("__ALSOFT_REVERSE_X", "reverse-x")); compatflags.set(CompatFlags::ReverseY, checkflag("__ALSOFT_REVERSE_Y", "reverse-y")); compatflags.set(CompatFlags::ReverseZ, checkflag("__ALSOFT_REVERSE_Z", "reverse-z")); - aluInit(compatflags, ConfigValueFloat(nullptr, "game_compat", "nfc-scale").value_or(1.0f)); + aluInit(compatflags, ConfigValueFloat({}, "game_compat", "nfc-scale").value_or(1.0f)); } - Voice::InitMixer(ConfigValueStr(nullptr, nullptr, "resampler")); + Voice::InitMixer(ConfigValueStr({}, {}, "resampler")); - if(auto uhjfiltopt = ConfigValueStr(nullptr, "uhj", "decode-filter")) + if(auto uhjfiltopt = ConfigValueStr({}, "uhj", "decode-filter")) { if(al::strcasecmp(uhjfiltopt->c_str(), "fir256") == 0) UhjDecodeQuality = UhjQualityType::FIR256; @@ -518,7 +518,7 @@ void alc_initconfig() else WARN("Unsupported uhj/decode-filter: %s\n", uhjfiltopt->c_str()); } - if(auto uhjfiltopt = ConfigValueStr(nullptr, "uhj", "encode-filter")) + if(auto uhjfiltopt = ConfigValueStr({}, "uhj", "encode-filter")) { if(al::strcasecmp(uhjfiltopt->c_str(), "fir256") == 0) UhjEncodeQuality = UhjQualityType::FIR256; @@ -544,17 +544,17 @@ void alc_initconfig() TrapALError = al::strcasecmp(traperr->c_str(), "true") == 0 || strtol(traperr->c_str(), nullptr, 0) == 1; else - TrapALError = !!GetConfigValueBool(nullptr, nullptr, "trap-al-error", false); + TrapALError = GetConfigValueBool({}, {}, "trap-al-error", false); traperr = al::getenv("ALSOFT_TRAP_ALC_ERROR"); if(traperr) TrapALCError = al::strcasecmp(traperr->c_str(), "true") == 0 || strtol(traperr->c_str(), nullptr, 0) == 1; else - TrapALCError = !!GetConfigValueBool(nullptr, nullptr, "trap-alc-error", false); + TrapALCError = GetConfigValueBool({}, {}, "trap-alc-error", false); } - if(auto boostopt = ConfigValueFloat(nullptr, "reverb", "boost")) + if(auto boostopt = ConfigValueFloat({}, "reverb", "boost")) { const float valf{std::isfinite(*boostopt) ? clampf(*boostopt, -24.0f, 24.0f) : 0.0f}; ReverbBoost *= std::pow(10.0f, valf / 20.0f); @@ -562,7 +562,7 @@ void alc_initconfig() auto BackendListEnd = std::end(BackendList); auto devopt = al::getenv("ALSOFT_DRIVERS"); - if(devopt || (devopt=ConfigValueStr(nullptr, nullptr, "drivers"))) + if(devopt || (devopt=ConfigValueStr({}, {}, "drivers"))) { auto backendlist_cur = std::begin(BackendList); @@ -648,7 +648,7 @@ void alc_initconfig() if(!CaptureFactory) WARN("No capture backend available!\n"); - if(auto exclopt = ConfigValueStr(nullptr, nullptr, "excludefx")) + if(auto exclopt = ConfigValueStr({}, {}, "excludefx")) { const char *next{exclopt->c_str()}; do { @@ -670,14 +670,12 @@ void alc_initconfig() InitEffect(&ALCcontext::sDefaultEffect); auto defrevopt = al::getenv("ALSOFT_DEFAULT_REVERB"); - if(defrevopt || (defrevopt=ConfigValueStr(nullptr, nullptr, "default-reverb"))) + if(defrevopt || (defrevopt=ConfigValueStr({}, {}, "default-reverb"))) LoadReverbPreset(defrevopt->c_str(), &ALCcontext::sDefaultEffect); #ifdef ALSOFT_EAX { - const char *eax_block_name{"eax"}; - - if(const auto eax_enable_opt = ConfigValueBool(nullptr, eax_block_name, "enable")) + if(const auto eax_enable_opt = ConfigValueBool({}, "eax", "enable")) { eax_g_is_enabled = *eax_enable_opt; if(!eax_g_is_enabled) @@ -1021,7 +1019,7 @@ ALCenum UpdateDeviceParams(ALCdevice *device, const int *attrList) { /* Get default settings from the user configuration */ - if(auto freqopt = device->configValue(nullptr, "frequency")) + if(auto freqopt = device->configValue({}, "frequency")) { optsrate = clampu(*freqopt, MinOutputRate, MaxOutputRate); @@ -1029,14 +1027,14 @@ ALCenum UpdateDeviceParams(ALCdevice *device, const int *attrList) period_size = static_cast(period_size*scale + 0.5); } - if(auto persizeopt = device->configValue(nullptr, "period_size")) + if(auto persizeopt = device->configValue({}, "period_size")) period_size = clampu(*persizeopt, 64, 8192); - if(auto numperopt = device->configValue(nullptr, "periods")) + if(auto numperopt = device->configValue({}, "periods")) buffer_size = clampu(*numperopt, 2, 16) * period_size; else buffer_size = period_size * uint{DefaultNumUpdates}; - if(auto typeopt = device->configValue(nullptr, "sample-type")) + if(auto typeopt = device->configValue({}, "sample-type")) { struct TypeMap { const char name[8]; /* NOLINT(*-avoid-c-arrays) */ @@ -1061,7 +1059,7 @@ ALCenum UpdateDeviceParams(ALCdevice *device, const int *attrList) else opttype = iter->type; } - if(auto chanopt = device->configValue(nullptr, "channels")) + if(auto chanopt = device->configValue({}, "channels")) { struct ChannelMap { const char name[16]; /* NOLINT(*-avoid-c-arrays) */ @@ -1095,7 +1093,7 @@ ALCenum UpdateDeviceParams(ALCdevice *device, const int *attrList) aorder = iter->order; } } - if(auto ambiopt = device->configValue(nullptr, "ambi-format")) + if(auto ambiopt = device->configValue({}, "ambi-format")) { const ALCchar *fmt{ambiopt->c_str()}; if(al::strcasecmp(fmt, "fuma") == 0) @@ -1122,7 +1120,7 @@ ALCenum UpdateDeviceParams(ALCdevice *device, const int *attrList) ERR("Unsupported ambi-format: %s\n", fmt); } - if(auto hrtfopt = device->configValue(nullptr, "hrtf")) + if(auto hrtfopt = device->configValue({}, "hrtf")) { WARN("general/hrtf is deprecated, please use stereo-encoding instead\n"); @@ -1139,7 +1137,7 @@ ALCenum UpdateDeviceParams(ALCdevice *device, const int *attrList) } } - if(auto encopt = device->configValue(nullptr, "stereo-encoding")) + if(auto encopt = device->configValue({}, "stereo-encoding")) { const char *mode{encopt->c_str()}; if(al::strcasecmp(mode, "basic") == 0 || al::strcasecmp(mode, "panpot") == 0) @@ -1475,7 +1473,7 @@ ALCenum UpdateDeviceParams(ALCdevice *device, const int *attrList) if(device->Type != DeviceType::Loopback) { - if(auto modeopt = device->configValue(nullptr, "stereo-mode")) + if(auto modeopt = device->configValue({}, "stereo-mode")) { const char *mode{modeopt->c_str()}; if(al::strcasecmp(mode, "headphones") == 0) @@ -1492,7 +1490,7 @@ ALCenum UpdateDeviceParams(ALCdevice *device, const int *attrList) /* Calculate the max number of sources, and split them between the mono and * stereo count given the requested number of stereo sources. */ - if(auto srcsopt = device->configValue(nullptr, "sources")) + if(auto srcsopt = device->configValue({}, "sources")) { if(*srcsopt <= 0) numMono = 256; else numMono = maxu(*srcsopt, 16); @@ -1508,7 +1506,7 @@ ALCenum UpdateDeviceParams(ALCdevice *device, const int *attrList) device->NumMonoSources = numMono; device->NumStereoSources = numStereo; - if(auto sendsopt = device->configValue(nullptr, "sends")) + if(auto sendsopt = device->configValue({}, "sends")) numSends = minu(numSends, static_cast(clampi(*sendsopt, 0, MaxSendCount))); device->NumAuxSends = numSends; @@ -1536,9 +1534,9 @@ ALCenum UpdateDeviceParams(ALCdevice *device, const int *attrList) if(auto *encoder{device->mUhjEncoder.get()}) sample_delay += encoder->getDelay(); - if(device->getConfigValueBool(nullptr, "dither", true)) + if(device->getConfigValueBool({}, "dither", true)) { - int depth{device->configValue(nullptr, "dither-depth").value_or(0)}; + int depth{device->configValue({}, "dither-depth").value_or(0)}; if(depth <= 0) { switch(device->FmtType) @@ -1571,7 +1569,7 @@ ALCenum UpdateDeviceParams(ALCdevice *device, const int *attrList) device->DitherDepth); if(!optlimit) - optlimit = device->configValue(nullptr, "output-limiter"); + optlimit = device->configValue({}, "output-limiter"); /* If the gain limiter is unset, use the limiter for integer-based output * (where samples must be clamped), and don't for floating-point (which can @@ -2696,7 +2694,7 @@ ALC_API ALCcontext* ALC_APIENTRY alcCreateContext(ALCdevice *device, const ALCin } context->init(); - if(auto volopt = dev->configValue(nullptr, "volume-adjust")) + if(auto volopt = dev->configValue({}, "volume-adjust")) { const float valf{*volopt}; if(!std::isfinite(valf)) diff --git a/alc/alconfig.cpp b/alc/alconfig.cpp index c9936725..d9e97e09 100644 --- a/alc/alconfig.cpp +++ b/alc/alconfig.cpp @@ -277,16 +277,19 @@ void LoadConfigFromFile(std::istream &f) ConfOpts.shrink_to_fit(); } -const char *GetConfigValue(const char *devName, const char *blockName, const char *keyName) +const char *GetConfigValue(const std::string_view devName, const std::string_view blockName, + const std::string_view keyName) { - if(!keyName) + if(keyName.empty()) return nullptr; + auto generalName = std::string_view{"general"}; std::string key; - if(blockName && al::strcasecmp(blockName, "general") != 0) + if(!blockName.empty() && (blockName.size() != generalName.size() || + al::strncasecmp(blockName.data(), generalName.data(), blockName.size()) != 0)) { key = blockName; - if(devName) + if(!devName.empty()) { key += '/'; key += devName; @@ -296,7 +299,7 @@ const char *GetConfigValue(const char *devName, const char *blockName, const cha } else { - if(devName) + if(!devName.empty()) { key = devName; key += '/'; @@ -315,9 +318,9 @@ const char *GetConfigValue(const char *devName, const char *blockName, const cha return nullptr; } - if(!devName) + if(devName.empty()) return nullptr; - return GetConfigValue(nullptr, blockName, keyName); + return GetConfigValue({}, blockName, keyName); } } // namespace @@ -489,35 +492,40 @@ void ReadALConfig() } #endif -std::optional ConfigValueStr(const char *devName, const char *blockName, const char *keyName) +std::optional ConfigValueStr(const std::string_view devName, + const std::string_view blockName, const std::string_view keyName) { if(const char *val{GetConfigValue(devName, blockName, keyName)}) return val; return std::nullopt; } -std::optional ConfigValueInt(const char *devName, const char *blockName, const char *keyName) +std::optional ConfigValueInt(const std::string_view devName, const std::string_view blockName, + const std::string_view keyName) { if(const char *val{GetConfigValue(devName, blockName, keyName)}) return static_cast(std::strtol(val, nullptr, 0)); return std::nullopt; } -std::optional ConfigValueUInt(const char *devName, const char *blockName, const char *keyName) +std::optional ConfigValueUInt(const std::string_view devName, + const std::string_view blockName, const std::string_view keyName) { if(const char *val{GetConfigValue(devName, blockName, keyName)}) return static_cast(std::strtoul(val, nullptr, 0)); return std::nullopt; } -std::optional ConfigValueFloat(const char *devName, const char *blockName, const char *keyName) +std::optional ConfigValueFloat(const std::string_view devName, + const std::string_view blockName, const std::string_view keyName) { if(const char *val{GetConfigValue(devName, blockName, keyName)}) return std::strtof(val, nullptr); return std::nullopt; } -std::optional ConfigValueBool(const char *devName, const char *blockName, const char *keyName) +std::optional ConfigValueBool(const std::string_view devName, + const std::string_view blockName, const std::string_view keyName) { if(const char *val{GetConfigValue(devName, blockName, keyName)}) return al::strcasecmp(val, "on") == 0 || al::strcasecmp(val, "yes") == 0 @@ -525,7 +533,8 @@ std::optional ConfigValueBool(const char *devName, const char *blockName, return std::nullopt; } -bool GetConfigValueBool(const char *devName, const char *blockName, const char *keyName, bool def) +bool GetConfigValueBool(const std::string_view devName, const std::string_view blockName, + const std::string_view keyName, bool def) { if(const char *val{GetConfigValue(devName, blockName, keyName)}) return (al::strcasecmp(val, "on") == 0 || al::strcasecmp(val, "yes") == 0 diff --git a/alc/alconfig.h b/alc/alconfig.h index 1eb44405..e7daac28 100644 --- a/alc/alconfig.h +++ b/alc/alconfig.h @@ -3,16 +3,23 @@ #include #include +#include void ReadALConfig(); -bool GetConfigValueBool(const char *devName, const char *blockName, const char *keyName, bool def); +bool GetConfigValueBool(const std::string_view devName, const std::string_view blockName, + const std::string_view keyName, bool def); -std::optional ConfigValueStr(const char *devName, const char *blockName, const char *keyName); -std::optional ConfigValueInt(const char *devName, const char *blockName, const char *keyName); -std::optional ConfigValueUInt(const char *devName, const char *blockName, const char *keyName); -std::optional ConfigValueFloat(const char *devName, const char *blockName, const char *keyName); -std::optional ConfigValueBool(const char *devName, const char *blockName, const char *keyName); +std::optional ConfigValueStr(const std::string_view devName, + const std::string_view blockName, const std::string_view keyName); +std::optional ConfigValueInt(const std::string_view devName, const std::string_view blockName, + const std::string_view keyName); +std::optional ConfigValueUInt(const std::string_view devName, + const std::string_view blockName, const std::string_view keyName); +std::optional ConfigValueFloat(const std::string_view devName, + const std::string_view blockName, const std::string_view keyName); +std::optional ConfigValueBool(const std::string_view devName, + const std::string_view blockName, const std::string_view keyName); #endif /* ALCONFIG_H */ diff --git a/alc/backends/alsa.cpp b/alc/backends/alsa.cpp index 344c440c..9bbcb241 100644 --- a/alc/backends/alsa.cpp +++ b/alc/backends/alsa.cpp @@ -253,10 +253,11 @@ std::vector PlaybackDevices; std::vector CaptureDevices; -const char *prefix_name(snd_pcm_stream_t stream) +const std::string_view prefix_name(snd_pcm_stream_t stream) { - assert(stream == SND_PCM_STREAM_PLAYBACK || stream == SND_PCM_STREAM_CAPTURE); - return (stream==SND_PCM_STREAM_PLAYBACK) ? "device-prefix" : "capture-prefix"; + if(stream == SND_PCM_STREAM_PLAYBACK) + return "device-prefix"; + return "capture-prefix"; } std::vector probe_devices(snd_pcm_stream_t stream) @@ -268,11 +269,11 @@ std::vector probe_devices(snd_pcm_stream_t stream) snd_pcm_info_t *pcminfo; snd_pcm_info_malloc(&pcminfo); - auto defname = ConfigValueStr(nullptr, "alsa", + auto defname = ConfigValueStr({}, "alsa", (stream == SND_PCM_STREAM_PLAYBACK) ? "device" : "capture"); devlist.emplace_back(alsaDevice, defname ? defname->c_str() : "default"); - if(auto customdevs = ConfigValueStr(nullptr, "alsa", + if(auto customdevs = ConfigValueStr({}, "alsa", (stream == SND_PCM_STREAM_PLAYBACK) ? "custom-devices" : "custom-captures")) { size_t nextpos{customdevs->find_first_not_of(';')}; @@ -300,8 +301,8 @@ std::vector probe_devices(snd_pcm_stream_t stream) } } - const std::string main_prefix{ - ConfigValueStr(nullptr, "alsa", prefix_name(stream)).value_or("plughw:")}; + const std::string main_prefix{ConfigValueStr({}, "alsa", prefix_name(stream)) + .value_or("plughw:")}; int card{-1}; int err{snd_card_next(&card)}; @@ -327,8 +328,7 @@ std::vector probe_devices(snd_pcm_stream_t stream) name = prefix_name(stream); name += '-'; name += cardid; - const std::string card_prefix{ - ConfigValueStr(nullptr, "alsa", name.c_str()).value_or(main_prefix)}; + const std::string card_prefix{ConfigValueStr({}, "alsa", name).value_or(main_prefix)}; int dev{-1}; while(true) @@ -353,8 +353,7 @@ std::vector probe_devices(snd_pcm_stream_t stream) name += cardid; name += '-'; name += std::to_string(dev); - const std::string device_prefix{ - ConfigValueStr(nullptr, "alsa", name.c_str()).value_or(card_prefix)}; + const std::string device_prefix{ConfigValueStr({},"alsa", name).value_or(card_prefix)}; /* "CardName, PcmName (CARD=cardid,DEV=dev)" */ name = cardname; @@ -643,7 +642,7 @@ void AlsaPlayback::open(std::string_view name) else { name = alsaDevice; - if(auto driveropt = ConfigValueStr(nullptr, "alsa", "device")) + if(auto driveropt = ConfigValueStr({}, "alsa", "device")) driver = std::move(driveropt).value(); } TRACE("Opening device \"%s\"\n", driver.c_str()); @@ -691,7 +690,7 @@ bool AlsaPlayback::reset() break; } - bool allowmmap{!!GetConfigValueBool(mDevice->DeviceName.c_str(), "alsa", "mmap", true)}; + bool allowmmap{GetConfigValueBool(mDevice->DeviceName, "alsa", "mmap", true)}; uint periodLen{static_cast(mDevice->UpdateSize * 1000000_u64 / mDevice->Frequency)}; uint bufferLen{static_cast(mDevice->BufferSize * 1000000_u64 / mDevice->Frequency)}; uint rate{mDevice->Frequency}; @@ -750,7 +749,7 @@ bool AlsaPlayback::reset() else mDevice->FmtChans = DevFmtStereo; } /* set rate (implicitly constrains period/buffer parameters) */ - if(!GetConfigValueBool(mDevice->DeviceName.c_str(), "alsa", "allow-resampler", false) + if(!GetConfigValueBool(mDevice->DeviceName, "alsa", "allow-resampler", false) || !mDevice->Flags.test(FrequencyRequest)) { if(snd_pcm_hw_params_set_rate_resample(mPcmHandle, hp.get(), 0) < 0) @@ -914,7 +913,7 @@ void AlsaCapture::open(std::string_view name) else { name = alsaDevice; - if(auto driveropt = ConfigValueStr(nullptr, "alsa", "capture")) + if(auto driveropt = ConfigValueStr({}, "alsa", "capture")) driver = std::move(driveropt).value(); } diff --git a/alc/backends/jack.cpp b/alc/backends/jack.cpp index eb87b0a7..922873b8 100644 --- a/alc/backends/jack.cpp +++ b/alc/backends/jack.cpp @@ -210,7 +210,7 @@ void EnumerateDevices(jack_client_t *client, std::vector &list) } } - if(auto listopt = ConfigValueStr(nullptr, "jack", "custom-devices")) + if(auto listopt = ConfigValueStr({}, "jack", "custom-devices")) { for(size_t strpos{0};strpos < listopt->size();) { @@ -509,7 +509,7 @@ bool JackPlayback::reset() std::for_each(mPort.begin(), mPort.end(), unregister_port); mPort.fill(nullptr); - mRTMixing = GetConfigValueBool(mDevice->DeviceName.c_str(), "jack", "rt-mix", true); + mRTMixing = GetConfigValueBool(mDevice->DeviceName, "jack", "rt-mix", true); jack_set_process_callback(mClient, mRTMixing ? &JackPlayback::processRtC : &JackPlayback::processC, this); @@ -527,7 +527,7 @@ bool JackPlayback::reset() } else { - const char *devname{mDevice->DeviceName.c_str()}; + const std::string_view devname{mDevice->DeviceName}; uint bufsize{ConfigValueUInt(devname, "jack", "buffer-size").value_or(mDevice->UpdateSize)}; bufsize = maxu(NextPowerOf2(bufsize), mDevice->UpdateSize); mDevice->BufferSize = bufsize + mDevice->UpdateSize; @@ -577,7 +577,7 @@ void JackPlayback::start() if(jack_activate(mClient)) throw al::backend_exception{al::backend_error::DeviceError, "Failed to activate client"}; - const char *devname{mDevice->DeviceName.c_str()}; + const std::string_view devname{mDevice->DeviceName}; if(ConfigValueBool(devname, "jack", "connect-ports").value_or(true)) { JackPortsPtr pnames{jack_get_ports(mClient, mPortPattern.c_str(), JackDefaultAudioType, @@ -676,7 +676,7 @@ bool JackBackendFactory::init() if(!jack_load()) return false; - if(!GetConfigValueBool(nullptr, "jack", "spawn-server", false)) + if(!GetConfigValueBool({}, "jack", "spawn-server", false)) ClientOptions = static_cast(ClientOptions | JackNoStartServer); const PathNamePair &binname = GetProcBinary(); diff --git a/alc/backends/oss.cpp b/alc/backends/oss.cpp index 8e547497..9a4aa9a8 100644 --- a/alc/backends/oss.cpp +++ b/alc/backends/oss.cpp @@ -631,9 +631,9 @@ BackendFactory &OSSBackendFactory::getFactory() bool OSSBackendFactory::init() { - if(auto devopt = ConfigValueStr(nullptr, "oss", "device")) + if(auto devopt = ConfigValueStr({}, "oss", "device")) DefaultPlayback = std::move(*devopt); - if(auto capopt = ConfigValueStr(nullptr, "oss", "capture")) + if(auto capopt = ConfigValueStr({}, "oss", "capture")) DefaultCapture = std::move(*capopt); return true; diff --git a/alc/backends/pipewire.cpp b/alc/backends/pipewire.cpp index d3ab8984..7b206d2d 100644 --- a/alc/backends/pipewire.cpp +++ b/alc/backends/pipewire.cpp @@ -1688,7 +1688,7 @@ bool PipeWirePlayback::reset() pw_stream_flags flags{PW_STREAM_FLAG_AUTOCONNECT | PW_STREAM_FLAG_INACTIVE | PW_STREAM_FLAG_MAP_BUFFERS}; - if(GetConfigValueBool(mDevice->DeviceName.c_str(), "pipewire", "rt-mix", false)) + if(GetConfigValueBool(mDevice->DeviceName, "pipewire", "rt-mix", false)) flags |= PW_STREAM_FLAG_RT_PROCESS; if(int res{pw_stream_connect(mStream.get(), PW_DIRECTION_OUTPUT, PwIdAny, flags, ¶ms, 1)}) throw al::backend_exception{al::backend_error::DeviceError, @@ -2191,7 +2191,7 @@ bool PipeWireBackendFactory::init() if(!gEventHandler.init()) return false; - if(!GetConfigValueBool(nullptr, "pipewire", "assume-audio", false) + if(!GetConfigValueBool({}, "pipewire", "assume-audio", false) && !gEventHandler.waitForAudio()) { gEventHandler.kill(); diff --git a/alc/backends/portaudio.cpp b/alc/backends/portaudio.cpp index b6013dcc..15a0f3ac 100644 --- a/alc/backends/portaudio.cpp +++ b/alc/backends/portaudio.cpp @@ -117,7 +117,7 @@ void PortPlayback::open(std::string_view name) static_cast(name.length()), name.data()}; PaStreamParameters params{}; - auto devidopt = ConfigValueInt(nullptr, "port", "device"); + auto devidopt = ConfigValueInt({}, "port", "device"); if(devidopt && *devidopt >= 0) params.device = *devidopt; else params.device = Pa_GetDefaultOutputDevice(); params.suggestedLatency = mDevice->BufferSize / static_cast(mDevice->Frequency); @@ -280,7 +280,7 @@ void PortCapture::open(std::string_view name) mRing = RingBuffer::Create(samples, frame_size, false); - auto devidopt = ConfigValueInt(nullptr, "port", "capture"); + auto devidopt = ConfigValueInt({}, "port", "capture"); if(devidopt && *devidopt >= 0) mParams.device = *devidopt; else mParams.device = Pa_GetDefaultOutputDevice(); mParams.suggestedLatency = 0.0f; diff --git a/alc/backends/pulseaudio.cpp b/alc/backends/pulseaudio.cpp index aec91229..6d842475 100644 --- a/alc/backends/pulseaudio.cpp +++ b/alc/backends/pulseaudio.cpp @@ -808,7 +808,7 @@ void PulsePlayback::open(std::string_view name) pa_stream_flags_t flags{PA_STREAM_START_CORKED | PA_STREAM_FIX_FORMAT | PA_STREAM_FIX_RATE | PA_STREAM_FIX_CHANNELS}; - if(!GetConfigValueBool(nullptr, "pulse", "allow-moves", true)) + if(!GetConfigValueBool({}, "pulse", "allow-moves", true)) flags |= PA_STREAM_DONT_MOVE; pa_sample_spec spec{}; @@ -867,9 +867,9 @@ bool PulsePlayback::reset() pa_stream_flags_t flags{PA_STREAM_START_CORKED | PA_STREAM_INTERPOLATE_TIMING | PA_STREAM_AUTO_TIMING_UPDATE | PA_STREAM_EARLY_REQUESTS}; - if(!GetConfigValueBool(nullptr, "pulse", "allow-moves", true)) + if(!GetConfigValueBool({}, "pulse", "allow-moves", true)) flags |= PA_STREAM_DONT_MOVE; - if(GetConfigValueBool(mDevice->DeviceName.c_str(), "pulse", "adjust-latency", false)) + if(GetConfigValueBool(mDevice->DeviceName, "pulse", "adjust-latency", false)) { /* ADJUST_LATENCY can't be specified with EARLY_REQUESTS, for some * reason. So if the user wants to adjust the overall device latency, @@ -878,7 +878,7 @@ bool PulsePlayback::reset() flags &= ~PA_STREAM_EARLY_REQUESTS; flags |= PA_STREAM_ADJUST_LATENCY; } - if(GetConfigValueBool(mDevice->DeviceName.c_str(), "pulse", "fix-rate", false) + if(GetConfigValueBool(mDevice->DeviceName, "pulse", "fix-rate", false) || !mDevice->Flags.test(FrequencyRequest)) flags |= PA_STREAM_FIX_RATE; @@ -1215,7 +1215,7 @@ void PulseCapture::open(std::string_view name) mAttr.fragsize = minu(samples, 50*mDevice->Frequency/1000) * frame_size; pa_stream_flags_t flags{PA_STREAM_START_CORKED | PA_STREAM_ADJUST_LATENCY}; - if(!GetConfigValueBool(nullptr, "pulse", "allow-moves", true)) + if(!GetConfigValueBool({}, "pulse", "allow-moves", true)) flags |= PA_STREAM_DONT_MOVE; TRACE("Connecting to \"%s\"\n", pulse_name ? pulse_name : "(default)"); @@ -1426,7 +1426,7 @@ bool PulseBackendFactory::init() #endif /* HAVE_DYNLOAD */ pulse_ctx_flags = PA_CONTEXT_NOFLAGS; - if(!GetConfigValueBool(nullptr, "pulse", "spawn-server", false)) + if(!GetConfigValueBool({}, "pulse", "spawn-server", false)) pulse_ctx_flags |= PA_CONTEXT_NOAUTOSPAWN; try { diff --git a/alc/backends/solaris.cpp b/alc/backends/solaris.cpp index b29a8cea..c7387284 100644 --- a/alc/backends/solaris.cpp +++ b/alc/backends/solaris.cpp @@ -265,7 +265,7 @@ BackendFactory &SolarisBackendFactory::getFactory() bool SolarisBackendFactory::init() { - if(auto devopt = ConfigValueStr(nullptr, "solaris", "device")) + if(auto devopt = ConfigValueStr({}, "solaris", "device")) solaris_driver = std::move(*devopt); return true; } diff --git a/alc/backends/wasapi.cpp b/alc/backends/wasapi.cpp index a164ed24..4fcae59c 100644 --- a/alc/backends/wasapi.cpp +++ b/alc/backends/wasapi.cpp @@ -1498,7 +1498,7 @@ void WasapiPlayback::prepareFormat(WAVEFORMATEXTENSIBLE &OutputType) void WasapiPlayback::finalizeFormat(WAVEFORMATEXTENSIBLE &OutputType) { - if(!GetConfigValueBool(mDevice->DeviceName.c_str(), "wasapi", "allow-resampler", true)) + if(!GetConfigValueBool(mDevice->DeviceName, "wasapi", "allow-resampler", true)) mDevice->Frequency = OutputType.Format.nSamplesPerSec; else mDevice->Frequency = minu(mDevice->Frequency, OutputType.Format.nSamplesPerSec); @@ -1612,7 +1612,7 @@ bool WasapiPlayback::reset() HRESULT WasapiPlayback::resetProxy() { - if(GetConfigValueBool(mDevice->DeviceName.c_str(), "wasapi", "spatial-api", false)) + if(GetConfigValueBool(mDevice->DeviceName, "wasapi", "spatial-api", false)) { auto &audio = mAudio.emplace(); HRESULT hr{sDeviceHelper->activateAudioClient(mMMDev, __uuidof(ISpatialAudioClient), @@ -1777,7 +1777,7 @@ HRESULT WasapiPlayback::resetProxy() mDevice->Flags.reset(DirectEar).set(Virtualization); if(streamParams.StaticObjectTypeMask == ChannelMask_Stereo) mDevice->FmtChans = DevFmtStereo; - if(!GetConfigValueBool(mDevice->DeviceName.c_str(), "wasapi", "allow-resampler", true)) + if(!GetConfigValueBool(mDevice->DeviceName, "wasapi", "allow-resampler", true)) mDevice->Frequency = OutputType.Format.nSamplesPerSec; else mDevice->Frequency = minu(mDevice->Frequency, OutputType.Format.nSamplesPerSec); diff --git a/alc/backends/wave.cpp b/alc/backends/wave.cpp index 11794608..95064906 100644 --- a/alc/backends/wave.cpp +++ b/alc/backends/wave.cpp @@ -195,7 +195,7 @@ int WaveBackend::mixerProc() void WaveBackend::open(std::string_view name) { - auto fname = ConfigValueStr(nullptr, "wave", "file"); + auto fname = ConfigValueStr({}, "wave", "file"); if(!fname) throw al::backend_exception{al::backend_error::NoDevice, "No wave output filename"}; @@ -231,7 +231,7 @@ bool WaveBackend::reset() fseek(mFile, 0, SEEK_SET); clearerr(mFile); - if(GetConfigValueBool(nullptr, "wave", "bformat", false)) + if(GetConfigValueBool({}, "wave", "bformat", false)) { mDevice->FmtChans = DevFmtAmbi3D; mDevice->mAmbiOrder = 1; diff --git a/alc/device.cpp b/alc/device.cpp index 5a34ad64..f13e6071 100644 --- a/alc/device.cpp +++ b/alc/device.cpp @@ -55,8 +55,8 @@ ALCdevice::~ALCdevice() void ALCdevice::enumerateHrtfs() { - mHrtfList = EnumerateHrtf(configValue(nullptr, "hrtf-paths")); - if(auto defhrtfopt = configValue(nullptr, "default-hrtf")) + mHrtfList = EnumerateHrtf(configValue({}, "hrtf-paths")); + if(auto defhrtfopt = configValue({}, "default-hrtf")) { auto iter = std::find(mHrtfList.begin(), mHrtfList.end(), *defhrtfopt); if(iter == mHrtfList.end()) diff --git a/alc/device.h b/alc/device.h index 0f36304b..4eb693ff 100644 --- a/alc/device.h +++ b/alc/device.h @@ -143,28 +143,28 @@ struct ALCdevice : public al::intrusive_ref, DeviceBase { void enumerateHrtfs(); - bool getConfigValueBool(const char *block, const char *key, bool def) - { return GetConfigValueBool(DeviceName.c_str(), block, key, def); } + bool getConfigValueBool(const std::string_view block, const std::string_view key, bool def) + { return GetConfigValueBool(DeviceName, block, key, def); } template - inline std::optional configValue(const char *block, const char *key) = delete; + inline std::optional configValue(const std::string_view block, const std::string_view key) = delete; }; template<> -inline std::optional ALCdevice::configValue(const char *block, const char *key) -{ return ConfigValueStr(DeviceName.c_str(), block, key); } +inline std::optional ALCdevice::configValue(const std::string_view block, const std::string_view key) +{ return ConfigValueStr(DeviceName, block, key); } template<> -inline std::optional ALCdevice::configValue(const char *block, const char *key) -{ return ConfigValueInt(DeviceName.c_str(), block, key); } +inline std::optional ALCdevice::configValue(const std::string_view block, const std::string_view key) +{ return ConfigValueInt(DeviceName, block, key); } template<> -inline std::optional ALCdevice::configValue(const char *block, const char *key) -{ return ConfigValueUInt(DeviceName.c_str(), block, key); } +inline std::optional ALCdevice::configValue(const std::string_view block, const std::string_view key) +{ return ConfigValueUInt(DeviceName, block, key); } template<> -inline std::optional ALCdevice::configValue(const char *block, const char *key) -{ return ConfigValueFloat(DeviceName.c_str(), block, key); } +inline std::optional ALCdevice::configValue(const std::string_view block, const std::string_view key) +{ return ConfigValueFloat(DeviceName, block, key); } template<> -inline std::optional ALCdevice::configValue(const char *block, const char *key) -{ return ConfigValueBool(DeviceName.c_str(), block, key); } +inline std::optional ALCdevice::configValue(const std::string_view block, const std::string_view key) +{ return ConfigValueBool(DeviceName, block, key); } /** Stores the latest ALC device error. */ void alcSetError(ALCdevice *device, ALCenum errorCode); diff --git a/alc/panning.cpp b/alc/panning.cpp index c0fe83ee..3b40687e 100644 --- a/alc/panning.cpp +++ b/alc/panning.cpp @@ -846,7 +846,7 @@ void InitHrtfPanning(ALCdevice *device) */ device->mRenderMode = RenderMode::Hrtf; uint ambi_order{1}; - if(auto modeopt = device->configValue(nullptr, "hrtf-mode")) + if(auto modeopt = device->configValue({}, "hrtf-mode")) { struct HrtfModeEntry { char name[7]; /* NOLINT(*-avoid-c-arrays) */ @@ -1024,7 +1024,7 @@ void aluInitRenderer(ALCdevice *device, int hrtf_id, std::optionalRealOut.ChannelIndex[FrontCenter] != InvalidChannelIndex && device->RealOut.ChannelIndex[FrontLeft] != InvalidChannelIndex && device->RealOut.ChannelIndex[FrontRight] != InvalidChannelIndex - && device->getConfigValueBool(nullptr, "front-stablizer", false) != 0}; + && device->getConfigValueBool({}, "front-stablizer", false) != 0}; const bool hqdec{device->getConfigValueBool("decoder", "hq-mode", true) != 0}; InitPanning(device, hqdec, stablize, decoder); if(decoder) @@ -1093,7 +1093,7 @@ void aluInitRenderer(ALCdevice *device, int hrtf_id, std::optionalmHrtf.get()}; device->mIrSize = hrtf->mIrSize; - if(auto hrtfsizeopt = device->configValue(nullptr, "hrtf-size")) + if(auto hrtfsizeopt = device->configValue({}, "hrtf-size")) { if(*hrtfsizeopt > 0 && *hrtfsizeopt < device->mIrSize) device->mIrSize = maxu(*hrtfsizeopt, MinIrLength); @@ -1132,7 +1132,7 @@ void aluInitRenderer(ALCdevice *device, int hrtf_id, std::optionalmRenderMode = RenderMode::Pairwise; if(device->Type != DeviceType::Loopback) { - if(auto cflevopt = device->configValue(nullptr, "cf_level")) + if(auto cflevopt = device->configValue({}, "cf_level")) { if(*cflevopt > 0 && *cflevopt <= 6) { -- cgit v1.2.3 From cfb6bdfabfdf70ce5bcb650d356c3a9c1db3df0c Mon Sep 17 00:00:00 2001 From: Chris Robinson Date: Sat, 23 Dec 2023 04:18:07 -0800 Subject: Avoid assignments in if conditions --- al/source.cpp | 4 ++-- alc/alc.cpp | 37 ++++++++++++++++++++----------------- alc/backends/alsa.cpp | 44 +++++++++++++++++++++++++++----------------- alc/backends/pipewire.cpp | 7 +++++-- alc/backends/portaudio.cpp | 3 ++- alc/backends/pulseaudio.cpp | 4 ++-- examples/alstreamcb.cpp | 3 ++- utils/makemhr/makemhr.cpp | 4 ++-- 8 files changed, 62 insertions(+), 44 deletions(-) (limited to 'alc/backends/pulseaudio.cpp') diff --git a/al/source.cpp b/al/source.cpp index c99943cf..f119ee36 100644 --- a/al/source.cpp +++ b/al/source.cpp @@ -3410,8 +3410,8 @@ FORCE_ALIGN void AL_APIENTRY alSourceQueueBuffersDirect(ALCcontext *context, ALu for(ALsizei i{0};i < nb;i++) { bool fmt_mismatch{false}; - ALbuffer *buffer{nullptr}; - if(buffers[i] && (buffer=LookupBuffer(device, buffers[i])) == nullptr) + ALbuffer *buffer{buffers[i] ? LookupBuffer(device, buffers[i]) : nullptr}; + if(buffers[i] && !buffer) { context->setError(AL_INVALID_NAME, "Queueing invalid buffer ID %u", buffers[i]); goto buffer_error; diff --git a/alc/alc.cpp b/alc/alc.cpp index 3ad07aaa..d944cf0c 100644 --- a/alc/alc.cpp +++ b/alc/alc.cpp @@ -562,7 +562,8 @@ void alc_initconfig() auto BackendListEnd = std::end(BackendList); auto devopt = al::getenv("ALSOFT_DRIVERS"); - if(devopt || (devopt=ConfigValueStr({}, {}, "drivers"))) + if(!devopt) devopt = ConfigValueStr({}, {}, "drivers"); + if(devopt) { auto backendlist_cur = std::begin(BackendList); @@ -670,8 +671,8 @@ void alc_initconfig() InitEffect(&ALCcontext::sDefaultEffect); auto defrevopt = al::getenv("ALSOFT_DEFAULT_REVERB"); - if(defrevopt || (defrevopt=ConfigValueStr({}, {}, "default-reverb"))) - LoadReverbPreset(defrevopt->c_str(), &ALCcontext::sDefaultEffect); + if(!defrevopt) defrevopt = ConfigValueStr({}, {}, "default-reverb"); + if(defrevopt) LoadReverbPreset(defrevopt->c_str(), &ALCcontext::sDefaultEffect); #ifdef ALSOFT_EAX { @@ -2556,23 +2557,25 @@ ALC_API ALCboolean ALC_APIENTRY alcIsExtensionPresent(ALCdevice *device, const A { DeviceRef dev{VerifyDevice(device)}; if(!extName) + { alcSetError(dev.get(), ALC_INVALID_VALUE); - else + return ALC_FALSE; + } + + const std::string_view tofind{extName}; + auto extlist = dev ? std::string_view{alcExtensionList} : std::string_view{alcNoDeviceExtList}; + while(!extlist.empty()) { - size_t len = strlen(extName); - const char *ptr = (dev ? alcExtensionList : alcNoDeviceExtList); - while(ptr && *ptr) - { - if(al::strncasecmp(ptr, extName, len) == 0 && (ptr[len] == '\0' || isspace(ptr[len]))) - return ALC_TRUE; + auto nextpos = extlist.find(' '); + auto tocheck = extlist.substr(0, nextpos); + if(tocheck.size() == tofind.size() + && al::strncasecmp(tofind.data(), tocheck.data(), tofind.size()) == 0) + return ALC_TRUE; - if((ptr=strchr(ptr, ' ')) != nullptr) - { - do { - ++ptr; - } while(isspace(*ptr)); - } - } + if(nextpos == std::string_view::npos) + break; + + extlist.remove_prefix(nextpos+1); } return ALC_FALSE; } diff --git a/alc/backends/alsa.cpp b/alc/backends/alsa.cpp index 9bbcb241..d7dd16c0 100644 --- a/alc/backends/alsa.cpp +++ b/alc/backends/alsa.cpp @@ -311,12 +311,14 @@ std::vector probe_devices(snd_pcm_stream_t stream) std::string name{"hw:" + std::to_string(card)}; snd_ctl_t *handle; - if((err=snd_ctl_open(&handle, name.c_str(), 0)) < 0) + err = snd_ctl_open(&handle, name.c_str(), 0); + if(err < 0) { ERR("control open (hw:%d): %s\n", card, snd_strerror(err)); continue; } - if((err=snd_ctl_card_info(handle, info)) < 0) + err = snd_ctl_card_info(handle, info); + if(err < 0) { ERR("control hardware info (hw:%d): %s\n", card, snd_strerror(err)); snd_ctl_close(handle); @@ -340,7 +342,8 @@ std::vector probe_devices(snd_pcm_stream_t stream) snd_pcm_info_set_device(pcminfo, static_cast(dev)); snd_pcm_info_set_subdevice(pcminfo, 0); snd_pcm_info_set_stream(pcminfo, stream); - if((err=snd_ctl_pcm_info(handle, pcminfo)) < 0) + err = snd_ctl_pcm_info(handle, pcminfo); + if(err < 0) { if(err != -ENOENT) ERR("control digital audio info (hw:%d): %s\n", card, snd_strerror(err)); @@ -405,13 +408,14 @@ int verify_state(snd_pcm_t *handle) break; case SND_PCM_STATE_XRUN: - if((err=snd_pcm_recover(handle, -EPIPE, 1)) < 0) - return err; + err=snd_pcm_recover(handle, -EPIPE, 1); + if(err < 0) return err; break; case SND_PCM_STATE_SUSPENDED: - if((err=snd_pcm_recover(handle, -ESTRPIPE, 1)) < 0) - return err; + err = snd_pcm_recover(handle, -ESTRPIPE, 1); + if(err < 0) return err; break; + case SND_PCM_STATE_DISCONNECTED: return -ENODEV; } @@ -698,7 +702,8 @@ bool AlsaPlayback::reset() int err{}; HwParamsPtr hp{CreateHwParams()}; #define CHECK(x) do { \ - if((err=(x)) < 0) \ + err = (x); \ + if(err < 0) \ throw al::backend_exception{al::backend_error::DeviceError, #x " failed: %s", \ snd_strerror(err)}; \ } while(0) @@ -759,11 +764,11 @@ bool AlsaPlayback::reset() WARN("Failed to enable ALSA resampler\n"); CHECK(snd_pcm_hw_params_set_rate_near(mPcmHandle, hp.get(), &rate, nullptr)); /* set period time (implicitly constrains period/buffer parameters) */ - if((err=snd_pcm_hw_params_set_period_time_near(mPcmHandle, hp.get(), &periodLen, nullptr)) < 0) - ERR("snd_pcm_hw_params_set_period_time_near failed: %s\n", snd_strerror(err)); + err = snd_pcm_hw_params_set_period_time_near(mPcmHandle, hp.get(), &periodLen, nullptr); + if(err < 0) ERR("snd_pcm_hw_params_set_period_time_near failed: %s\n", snd_strerror(err)); /* set buffer time (implicitly sets buffer size/bytes/time and period size/bytes) */ - if((err=snd_pcm_hw_params_set_buffer_time_near(mPcmHandle, hp.get(), &bufferLen, nullptr)) < 0) - ERR("snd_pcm_hw_params_set_buffer_time_near failed: %s\n", snd_strerror(err)); + err = snd_pcm_hw_params_set_buffer_time_near(mPcmHandle, hp.get(), &bufferLen, nullptr); + if(err < 0) ERR("snd_pcm_hw_params_set_buffer_time_near failed: %s\n", snd_strerror(err)); /* install and prepare hardware configuration */ CHECK(snd_pcm_hw_params(mPcmHandle, hp.get())); @@ -801,7 +806,8 @@ void AlsaPlayback::start() snd_pcm_access_t access{}; HwParamsPtr hp{CreateHwParams()}; #define CHECK(x) do { \ - if((err=(x)) < 0) \ + err = (x); \ + if(err < 0) \ throw al::backend_exception{al::backend_error::DeviceError, #x " failed: %s", \ snd_strerror(err)}; \ } while(0) @@ -958,7 +964,8 @@ void AlsaCapture::open(std::string_view name) bool needring{false}; HwParamsPtr hp{CreateHwParams()}; #define CHECK(x) do { \ - if((err=(x)) < 0) \ + err = (x); \ + if(err < 0) \ throw al::backend_exception{al::backend_error::DeviceError, #x " failed: %s", \ snd_strerror(err)}; \ } while(0) @@ -1065,7 +1072,8 @@ void AlsaCapture::captureSamples(std::byte *buffer, uint samples) if(amt == -EAGAIN) continue; - if((amt=snd_pcm_recover(mPcmHandle, static_cast(amt), 1)) >= 0) + amt = snd_pcm_recover(mPcmHandle, static_cast(amt), 1); + if(amt >= 0) { amt = snd_pcm_start(mPcmHandle); if(amt >= 0) @@ -1102,7 +1110,8 @@ uint AlsaCapture::availableSamples() { ERR("avail update failed: %s\n", snd_strerror(static_cast(avail))); - if((avail=snd_pcm_recover(mPcmHandle, static_cast(avail), 1)) >= 0) + avail = snd_pcm_recover(mPcmHandle, static_cast(avail), 1); + if(avail >= 0) { if(mDoCapture) avail = snd_pcm_start(mPcmHandle); @@ -1138,7 +1147,8 @@ uint AlsaCapture::availableSamples() if(amt == -EAGAIN) continue; - if((amt=snd_pcm_recover(mPcmHandle, static_cast(amt), 1)) >= 0) + amt = snd_pcm_recover(mPcmHandle, static_cast(amt), 1); + if(amt >= 0) { if(mDoCapture) amt = snd_pcm_start(mPcmHandle); diff --git a/alc/backends/pipewire.cpp b/alc/backends/pipewire.cpp index 44b84296..2e6e20cc 100644 --- a/alc/backends/pipewire.cpp +++ b/alc/backends/pipewire.cpp @@ -1088,8 +1088,11 @@ void NodeProxy::paramCallback(int, uint32_t id, uint32_t, uint32_t, const spa_po if(const spa_pod_prop *prop{spa_pod_find_prop(param, nullptr, SPA_FORMAT_AUDIO_position)}) node->parsePositions(&prop->value, force_update); - else if((prop=spa_pod_find_prop(param, nullptr, SPA_FORMAT_AUDIO_channels)) != nullptr) - node->parseChannelCount(&prop->value, force_update); + else + { + prop = spa_pod_find_prop(param, nullptr, SPA_FORMAT_AUDIO_channels); + if(prop) node->parseChannelCount(&prop->value, force_update); + } } } diff --git a/alc/backends/portaudio.cpp b/alc/backends/portaudio.cpp index 15a0f3ac..2ccb1c64 100644 --- a/alc/backends/portaudio.cpp +++ b/alc/backends/portaudio.cpp @@ -394,7 +394,8 @@ bool PortBackendFactory::init() LOAD_FUNC(Pa_GetStreamInfo); #undef LOAD_FUNC - if((err=Pa_Initialize()) != paNoError) + err = Pa_Initialize(); + if(err != paNoError) { ERR("Pa_Initialize() returned an error: %s\n", Pa_GetErrorText(err)); CloseLib(pa_handle); diff --git a/alc/backends/pulseaudio.cpp b/alc/backends/pulseaudio.cpp index 6d842475..dcf01095 100644 --- a/alc/backends/pulseaudio.cpp +++ b/alc/backends/pulseaudio.cpp @@ -510,8 +510,8 @@ void MainloopUniqueLock::connectContext() pa_context_set_state_callback(mutex()->mContext, [](pa_context *ctx, void *pdata) noexcept { return static_cast(pdata)->contextStateCallback(ctx); }, this); - int err; - if((err=pa_context_connect(mutex()->mContext, nullptr, pulse_ctx_flags, nullptr)) >= 0) + int err{pa_context_connect(mutex()->mContext, nullptr, pulse_ctx_flags, nullptr)}; + if(err >= 0) { pa_context_state_t state; while((state=pa_context_get_state(mutex()->mContext)) != PA_CONTEXT_READY) diff --git a/examples/alstreamcb.cpp b/examples/alstreamcb.cpp index 1721d367..2da33b21 100644 --- a/examples/alstreamcb.cpp +++ b/examples/alstreamcb.cpp @@ -522,7 +522,8 @@ int main(int argc, char **argv) /* Get the name portion, without the path, for display. */ const char *namepart{strrchr(argv[i], '/')}; - if(namepart || (namepart=strrchr(argv[i], '\\'))) + if(!namepart) namepart = strrchr(argv[i], '\\'); + if(namepart) ++namepart; else namepart = argv[i]; diff --git a/utils/makemhr/makemhr.cpp b/utils/makemhr/makemhr.cpp index 2b6d04ce..f14110c0 100644 --- a/utils/makemhr/makemhr.cpp +++ b/utils/makemhr/makemhr.cpp @@ -342,9 +342,9 @@ static int StoreMhr(const HrirDataT *hData, const char *filename) const uint n{hData->mIrPoints}; uint dither_seed{22222}; uint fi, ei, ai, i; - FILE *fp; - if((fp=fopen(filename, "wb")) == nullptr) + FILE *fp{fopen(filename, "wb")}; + if(!fp) { fprintf(stderr, "\nError: Could not open MHR file '%s'.\n", filename); return 0; -- cgit v1.2.3 From 1fddc044ac765d00e64628e59edcbcd71f0046b1 Mon Sep 17 00:00:00 2001 From: Chris Robinson Date: Tue, 26 Dec 2023 00:02:23 -0800 Subject: Clean up some gotos and non-optimal casts --- al/effects/chorus.cpp | 4 +- al/effects/fshifter.cpp | 4 +- al/effects/modulator.cpp | 2 +- al/effects/vmorpher.cpp | 6 +- al/source.cpp | 146 +++++++++++++++++++++++--------------------- alc/alu.cpp | 12 ++-- alc/backends/oss.cpp | 14 +---- alc/backends/portaudio.cpp | 17 ++---- alc/backends/pulseaudio.cpp | 5 +- alc/backends/sndio.cpp | 131 ++++++++++++++++++++------------------- examples/alconvolve.c | 15 +++-- examples/alffplay.cpp | 3 +- examples/almultireverb.c | 6 +- examples/alstream.c | 9 ++- examples/alstreamcb.cpp | 4 +- utils/makemhr/loaddef.cpp | 6 +- 16 files changed, 190 insertions(+), 194 deletions(-) (limited to 'alc/backends/pulseaudio.cpp') diff --git a/al/effects/chorus.cpp b/al/effects/chorus.cpp index dba59d1d..913d1215 100644 --- a/al/effects/chorus.cpp +++ b/al/effects/chorus.cpp @@ -49,7 +49,7 @@ inline ALenum EnumFromWaveform(ChorusWaveform type) EffectProps genDefaultChorusProps() noexcept { ChorusProps props{}; - props.Waveform = *WaveformFromEnum(AL_CHORUS_DEFAULT_WAVEFORM); + props.Waveform = WaveformFromEnum(AL_CHORUS_DEFAULT_WAVEFORM).value(); props.Phase = AL_CHORUS_DEFAULT_PHASE; props.Rate = AL_CHORUS_DEFAULT_RATE; props.Depth = AL_CHORUS_DEFAULT_DEPTH; @@ -61,7 +61,7 @@ EffectProps genDefaultChorusProps() noexcept EffectProps genDefaultFlangerProps() noexcept { FlangerProps props{}; - props.Waveform = *WaveformFromEnum(AL_FLANGER_DEFAULT_WAVEFORM); + props.Waveform = WaveformFromEnum(AL_FLANGER_DEFAULT_WAVEFORM).value(); props.Phase = AL_FLANGER_DEFAULT_PHASE; props.Rate = AL_FLANGER_DEFAULT_RATE; props.Depth = AL_FLANGER_DEFAULT_DEPTH; diff --git a/al/effects/fshifter.cpp b/al/effects/fshifter.cpp index 6f19e0dd..556244ac 100644 --- a/al/effects/fshifter.cpp +++ b/al/effects/fshifter.cpp @@ -45,8 +45,8 @@ EffectProps genDefaultProps() noexcept { FshifterProps props{}; props.Frequency = AL_FREQUENCY_SHIFTER_DEFAULT_FREQUENCY; - props.LeftDirection = *DirectionFromEmum(AL_FREQUENCY_SHIFTER_DEFAULT_LEFT_DIRECTION); - props.RightDirection = *DirectionFromEmum(AL_FREQUENCY_SHIFTER_DEFAULT_RIGHT_DIRECTION); + props.LeftDirection = DirectionFromEmum(AL_FREQUENCY_SHIFTER_DEFAULT_LEFT_DIRECTION).value(); + props.RightDirection = DirectionFromEmum(AL_FREQUENCY_SHIFTER_DEFAULT_RIGHT_DIRECTION).value(); return props; } diff --git a/al/effects/modulator.cpp b/al/effects/modulator.cpp index 566b333e..7e9424c0 100644 --- a/al/effects/modulator.cpp +++ b/al/effects/modulator.cpp @@ -47,7 +47,7 @@ EffectProps genDefaultProps() noexcept ModulatorProps props{}; props.Frequency = AL_RING_MODULATOR_DEFAULT_FREQUENCY; props.HighPassCutoff = AL_RING_MODULATOR_DEFAULT_HIGHPASS_CUTOFF; - props.Waveform = *WaveformFromEmum(AL_RING_MODULATOR_DEFAULT_WAVEFORM); + props.Waveform = WaveformFromEmum(AL_RING_MODULATOR_DEFAULT_WAVEFORM).value(); return props; } diff --git a/al/effects/vmorpher.cpp b/al/effects/vmorpher.cpp index a986ddf7..35a64d32 100644 --- a/al/effects/vmorpher.cpp +++ b/al/effects/vmorpher.cpp @@ -126,11 +126,11 @@ EffectProps genDefaultProps() noexcept { VmorpherProps props{}; props.Rate = AL_VOCAL_MORPHER_DEFAULT_RATE; - props.PhonemeA = *PhenomeFromEnum(AL_VOCAL_MORPHER_DEFAULT_PHONEMEA); - props.PhonemeB = *PhenomeFromEnum(AL_VOCAL_MORPHER_DEFAULT_PHONEMEB); + props.PhonemeA = PhenomeFromEnum(AL_VOCAL_MORPHER_DEFAULT_PHONEMEA).value(); + props.PhonemeB = PhenomeFromEnum(AL_VOCAL_MORPHER_DEFAULT_PHONEMEB).value(); props.PhonemeACoarseTuning = AL_VOCAL_MORPHER_DEFAULT_PHONEMEA_COARSE_TUNING; props.PhonemeBCoarseTuning = AL_VOCAL_MORPHER_DEFAULT_PHONEMEB_COARSE_TUNING; - props.Waveform = *WaveformFromEmum(AL_VOCAL_MORPHER_DEFAULT_WAVEFORM); + props.Waveform = WaveformFromEmum(AL_VOCAL_MORPHER_DEFAULT_WAVEFORM).value(); return props; } diff --git a/al/source.cpp b/al/source.cpp index a440a04b..bf96a769 100644 --- a/al/source.cpp +++ b/al/source.cpp @@ -3407,90 +3407,94 @@ FORCE_ALIGN void AL_APIENTRY alSourceQueueBuffersDirect(ALCcontext *context, ALu std::unique_lock buflock{device->BufferLock}; const size_t NewListStart{source->mQueue.size()}; - ALbufferQueueItem *BufferList{nullptr}; - for(ALsizei i{0};i < nb;i++) - { - bool fmt_mismatch{false}; - ALbuffer *buffer{buffers[i] ? LookupBuffer(device, buffers[i]) : nullptr}; - if(buffers[i] && !buffer) - { - context->setError(AL_INVALID_NAME, "Queueing invalid buffer ID %u", buffers[i]); - goto buffer_error; - } - if(buffer) + try { + ALbufferQueueItem *BufferList{nullptr}; + for(ALsizei i{0};i < nb;i++) { - if(buffer->mSampleRate < 1) + bool fmt_mismatch{false}; + ALbuffer *buffer{buffers[i] ? LookupBuffer(device, buffers[i]) : nullptr}; + if(buffers[i] && !buffer) { - context->setError(AL_INVALID_OPERATION, "Queueing buffer %u with no format", - buffer->id); - goto buffer_error; + context->setError(AL_INVALID_NAME, "Queueing invalid buffer ID %u", buffers[i]); + throw std::exception{}; } - if(buffer->mCallback) + if(buffer) { - context->setError(AL_INVALID_OPERATION, "Queueing callback buffer %u", buffer->id); - goto buffer_error; + if(buffer->mSampleRate < 1) + { + context->setError(AL_INVALID_OPERATION, "Queueing buffer %u with no format", + buffer->id); + throw std::exception{}; + } + if(buffer->mCallback) + { + context->setError(AL_INVALID_OPERATION, "Queueing callback buffer %u", + buffer->id); + throw std::exception{}; + } + if(buffer->MappedAccess != 0 && !(buffer->MappedAccess&AL_MAP_PERSISTENT_BIT_SOFT)) + { + context->setError(AL_INVALID_OPERATION, + "Queueing non-persistently mapped buffer %u", buffer->id); + throw std::exception{}; + } } - if(buffer->MappedAccess != 0 && !(buffer->MappedAccess&AL_MAP_PERSISTENT_BIT_SOFT)) + + source->mQueue.emplace_back(); + if(!BufferList) + BufferList = &source->mQueue.back(); + else { - context->setError(AL_INVALID_OPERATION, - "Queueing non-persistently mapped buffer %u", buffer->id); - goto buffer_error; + auto &item = source->mQueue.back(); + BufferList->mNext.store(&item, std::memory_order_relaxed); + BufferList = &item; } - } - - source->mQueue.emplace_back(); - if(!BufferList) - BufferList = &source->mQueue.back(); - else - { - auto &item = source->mQueue.back(); - BufferList->mNext.store(&item, std::memory_order_relaxed); - BufferList = &item; - } - if(!buffer) continue; - BufferList->mBlockAlign = buffer->mBlockAlign; - BufferList->mSampleLen = buffer->mSampleLen; - BufferList->mLoopEnd = buffer->mSampleLen; - BufferList->mSamples = buffer->mData.data(); - BufferList->mBuffer = buffer; - IncrementRef(buffer->ref); - - if(BufferFmt == nullptr) - BufferFmt = buffer; - else - { - fmt_mismatch |= BufferFmt->mSampleRate != buffer->mSampleRate; - fmt_mismatch |= BufferFmt->mChannels != buffer->mChannels; - fmt_mismatch |= BufferFmt->mType != buffer->mType; - if(BufferFmt->isBFormat()) + if(!buffer) continue; + BufferList->mBlockAlign = buffer->mBlockAlign; + BufferList->mSampleLen = buffer->mSampleLen; + BufferList->mLoopEnd = buffer->mSampleLen; + BufferList->mSamples = buffer->mData.data(); + BufferList->mBuffer = buffer; + IncrementRef(buffer->ref); + + if(BufferFmt == nullptr) + BufferFmt = buffer; + else { - fmt_mismatch |= BufferFmt->mAmbiLayout != buffer->mAmbiLayout; - fmt_mismatch |= BufferFmt->mAmbiScaling != buffer->mAmbiScaling; + fmt_mismatch |= BufferFmt->mSampleRate != buffer->mSampleRate; + fmt_mismatch |= BufferFmt->mChannels != buffer->mChannels; + fmt_mismatch |= BufferFmt->mType != buffer->mType; + if(BufferFmt->isBFormat()) + { + fmt_mismatch |= BufferFmt->mAmbiLayout != buffer->mAmbiLayout; + fmt_mismatch |= BufferFmt->mAmbiScaling != buffer->mAmbiScaling; + } + fmt_mismatch |= BufferFmt->mAmbiOrder != buffer->mAmbiOrder; } - fmt_mismatch |= BufferFmt->mAmbiOrder != buffer->mAmbiOrder; - } - if(fmt_mismatch) UNLIKELY - { - context->setError(AL_INVALID_OPERATION, "Queueing buffer with mismatched format\n" - " Expected: %uhz, %s, %s ; Got: %uhz, %s, %s\n", BufferFmt->mSampleRate, - NameFromFormat(BufferFmt->mType), NameFromFormat(BufferFmt->mChannels), - buffer->mSampleRate, NameFromFormat(buffer->mType), - NameFromFormat(buffer->mChannels)); - - buffer_error: - /* A buffer failed (invalid ID or format), so unlock and release - * each buffer we had. - */ - auto iter = source->mQueue.begin() + ptrdiff_t(NewListStart); - for(;iter != source->mQueue.end();++iter) + if(fmt_mismatch) UNLIKELY { - if(ALbuffer *buf{iter->mBuffer}) - DecrementRef(buf->ref); + context->setError(AL_INVALID_OPERATION, "Queueing buffer with mismatched format\n" + " Expected: %uhz, %s, %s ; Got: %uhz, %s, %s\n", BufferFmt->mSampleRate, + NameFromFormat(BufferFmt->mType), NameFromFormat(BufferFmt->mChannels), + buffer->mSampleRate, NameFromFormat(buffer->mType), + NameFromFormat(buffer->mChannels)); + throw std::exception{}; } - source->mQueue.resize(NewListStart); - return; } } + catch(...) { + /* A buffer failed (invalid ID or format), or there was some other + * unexpected error, so unlock and release each buffer we had. + */ + auto iter = source->mQueue.begin() + ptrdiff_t(NewListStart); + for(;iter != source->mQueue.end();++iter) + { + if(ALbuffer *buf{iter->mBuffer}) + DecrementRef(buf->ref); + } + source->mQueue.resize(NewListStart); + return; + } /* All buffers good. */ buflock.unlock(); diff --git a/alc/alu.cpp b/alc/alu.cpp index eb3dee5f..9e7a758e 100644 --- a/alc/alu.cpp +++ b/alc/alu.cpp @@ -678,16 +678,16 @@ void AmbiRotator(AmbiRotateMatrix &matrix, const int order) auto P = [](const int i, const int l, const int a, const int n, const size_t last_band, const AmbiRotateMatrix &R) { - const float ri1{ R[ 1+2][static_cast(i+2)]}; - const float rim1{R[-1+2][static_cast(i+2)]}; - const float ri0{ R[ 0+2][static_cast(i+2)]}; + const float ri1{ R[ 1+2][static_cast(i+2_z)]}; + const float rim1{R[-1+2][static_cast(i+2_z)]}; + const float ri0{ R[ 0+2][static_cast(i+2_z)]}; const size_t y{last_band + static_cast(a+l-1)}; if(n == -l) - return ri1*R[last_band][y] + rim1*R[last_band + static_cast(l-1)*2][y]; + return ri1*R[last_band][y] + rim1*R[last_band + static_cast(l-1_z)*2][y]; if(n == l) - return ri1*R[last_band + static_cast(l-1)*2][y] - rim1*R[last_band][y]; - return ri0*R[last_band + static_cast(n+l-1)][y]; + return ri1*R[last_band + static_cast(l-1_z)*2][y] - rim1*R[last_band][y]; + return ri0*R[last_band + static_cast(l-1_z+n)][y]; }; auto U = [P](const int l, const int m, const int n, const size_t last_band, diff --git a/alc/backends/oss.cpp b/alc/backends/oss.cpp index 50bed5ee..d541b534 100644 --- a/alc/backends/oss.cpp +++ b/alc/backends/oss.cpp @@ -367,11 +367,9 @@ bool OSSPlayback::reset() uint numFragmentsLogSize{(periods << 16) | log2FragmentSize}; audio_buf_info info{}; - const char *err; -#define CHECKERR(func) if((func) < 0) { \ - err = #func; \ - goto err; \ -} +#define CHECKERR(func) if((func) < 0) \ + throw al::backend_exception{al::backend_error::DeviceError, "%s failed: %s\n", #func, strerror(errno)}; + /* Don't fail if SETFRAGMENT fails. We can handle just about anything * that's reported back via GETOSPACE */ ioctl(mFd, SNDCTL_DSP_SETFRAGMENT, &numFragmentsLogSize); @@ -379,12 +377,6 @@ bool OSSPlayback::reset() CHECKERR(ioctl(mFd, SNDCTL_DSP_CHANNELS, &numChannels)); CHECKERR(ioctl(mFd, SNDCTL_DSP_SPEED, &ossSpeed)); CHECKERR(ioctl(mFd, SNDCTL_DSP_GETOSPACE, &info)); - if(false) - { - err: - ERR("%s failed: %s\n", err, strerror(errno)); - return false; - } #undef CHECKERR if(mDevice->channelsFromFmt() != numChannels) diff --git a/alc/backends/portaudio.cpp b/alc/backends/portaudio.cpp index 2ccb1c64..a8bd00fd 100644 --- a/alc/backends/portaudio.cpp +++ b/alc/backends/portaudio.cpp @@ -148,7 +148,6 @@ void PortPlayback::open(std::string_view name) break; } -retry_open: static constexpr auto writeCallback = [](const void *inputBuffer, void *outputBuffer, unsigned long framesPerBuffer, const PaStreamCallbackTimeInfo *timeInfo, const PaStreamCallbackFlags statusFlags, void *userData) noexcept @@ -157,17 +156,13 @@ retry_open: framesPerBuffer, timeInfo, statusFlags); }; PaStream *stream{}; - PaError err{Pa_OpenStream(&stream, nullptr, ¶ms, mDevice->Frequency, mDevice->UpdateSize, - paNoFlag, writeCallback, this)}; - if(err != paNoError) + while(PaError err{Pa_OpenStream(&stream, nullptr, ¶ms, mDevice->Frequency, + mDevice->UpdateSize, paNoFlag, writeCallback, this)}) { - if(params.sampleFormat == paFloat32) - { - params.sampleFormat = paInt16; - goto retry_open; - } - throw al::backend_exception{al::backend_error::NoDevice, "Failed to open stream: %s", - Pa_GetErrorText(err)}; + if(params.sampleFormat != paFloat32) + throw al::backend_exception{al::backend_error::NoDevice, "Failed to open stream: %s", + Pa_GetErrorText(err)}; + params.sampleFormat = paInt16; } Pa_CloseStream(mStream); diff --git a/alc/backends/pulseaudio.cpp b/alc/backends/pulseaudio.cpp index dcf01095..77d45466 100644 --- a/alc/backends/pulseaudio.cpp +++ b/alc/backends/pulseaudio.cpp @@ -968,8 +968,9 @@ bool PulsePlayback::reset() const auto scale = static_cast(mSpec.rate) / mDevice->Frequency; const auto perlen = static_cast(clampd(scale*mDevice->UpdateSize + 0.5, 64.0, 8192.0)); - const auto buflen = static_cast(clampd(scale*mDevice->BufferSize + 0.5, perlen*2, - std::numeric_limits::max()/mFrameSize)); + const auto bufmax = uint{std::numeric_limits::max() / mFrameSize}; + const auto buflen = static_cast(clampd(scale*mDevice->BufferSize + 0.5, perlen*2.0, + bufmax)); mAttr.maxlength = ~0u; mAttr.tlength = buflen * mFrameSize; diff --git a/alc/backends/sndio.cpp b/alc/backends/sndio.cpp index 0e667874..ce3de366 100644 --- a/alc/backends/sndio.cpp +++ b/alc/backends/sndio.cpp @@ -135,72 +135,75 @@ bool SndioPlayback::reset() SioPar par; auto tryfmt = mDevice->FmtType; -retry_params: - switch(tryfmt) + while(true) { - case DevFmtByte: - par.bits = 8; - par.sig = 1; - break; - case DevFmtUByte: - par.bits = 8; - par.sig = 0; - break; - case DevFmtShort: - par.bits = 16; - par.sig = 1; - break; - case DevFmtUShort: - par.bits = 16; - par.sig = 0; - break; - case DevFmtFloat: - case DevFmtInt: - par.bits = 32; - par.sig = 1; - break; - case DevFmtUInt: - par.bits = 32; - par.sig = 0; - break; - } - par.bps = SIO_BPS(par.bits); - par.le = SIO_LE_NATIVE; - par.msb = 1; - - par.rate = mDevice->Frequency; - par.pchan = mDevice->channelsFromFmt(); - - par.round = mDevice->UpdateSize; - par.appbufsz = mDevice->BufferSize - mDevice->UpdateSize; - if(!par.appbufsz) par.appbufsz = mDevice->UpdateSize; + switch(tryfmt) + { + case DevFmtByte: + par.bits = 8; + par.sig = 1; + break; + case DevFmtUByte: + par.bits = 8; + par.sig = 0; + break; + case DevFmtShort: + par.bits = 16; + par.sig = 1; + break; + case DevFmtUShort: + par.bits = 16; + par.sig = 0; + break; + case DevFmtFloat: + case DevFmtInt: + par.bits = 32; + par.sig = 1; + break; + case DevFmtUInt: + par.bits = 32; + par.sig = 0; + break; + } + par.bps = SIO_BPS(par.bits); + par.le = SIO_LE_NATIVE; + par.msb = 1; + + par.rate = mDevice->Frequency; + par.pchan = mDevice->channelsFromFmt(); + + par.round = mDevice->UpdateSize; + par.appbufsz = mDevice->BufferSize - mDevice->UpdateSize; + if(!par.appbufsz) par.appbufsz = mDevice->UpdateSize; + + try { + if(!sio_setpar(mSndHandle, &par)) + throw al::backend_exception{al::backend_error::DeviceError, + "Failed to set device parameters"}; + + par.clear(); + if(!sio_getpar(mSndHandle, &par)) + throw al::backend_exception{al::backend_error::DeviceError, + "Failed to get device parameters"}; + + if(par.bps > 1 && par.le != SIO_LE_NATIVE) + throw al::backend_exception{al::backend_error::DeviceError, + "%s-endian samples not supported", par.le ? "Little" : "Big"}; + if(par.bits < par.bps*8 && !par.msb) + throw al::backend_exception{al::backend_error::DeviceError, + "MSB-padded samples not supported (%u of %u bits)", par.bits, par.bps*8}; + if(par.pchan < 1) + throw al::backend_exception{al::backend_error::DeviceError, + "No playback channels on device"}; - try { - if(!sio_setpar(mSndHandle, &par)) - throw al::backend_exception{al::backend_error::DeviceError, - "Failed to set device parameters"}; - - par.clear(); - if(!sio_getpar(mSndHandle, &par)) - throw al::backend_exception{al::backend_error::DeviceError, - "Failed to get device parameters"}; - - if(par.bps > 1 && par.le != SIO_LE_NATIVE) - throw al::backend_exception{al::backend_error::DeviceError, - "%s-endian samples not supported", par.le ? "Little" : "Big"}; - if(par.bits < par.bps*8 && !par.msb) - throw al::backend_exception{al::backend_error::DeviceError, - "MSB-padded samples not supported (%u of %u bits)", par.bits, par.bps*8}; - if(par.pchan < 1) - throw al::backend_exception{al::backend_error::DeviceError, - "No playback channels on device"}; - } - catch(al::backend_exception &e) { - if(tryfmt == DevFmtShort) - throw; - par.clear(); - tryfmt = DevFmtShort; - goto retry_params; + break; + } + catch(al::backend_exception &e) { + if(tryfmt == DevFmtShort) + throw; + par.clear(); + tryfmt = DevFmtShort; + } } if(par.bps == 1) diff --git a/examples/alconvolve.c b/examples/alconvolve.c index d194d270..597d6ea2 100644 --- a/examples/alconvolve.c +++ b/examples/alconvolve.c @@ -361,10 +361,10 @@ static ALuint LoadSound(const char *filename) } namepart = strrchr(filename, '/'); - if(namepart || (namepart=strrchr(filename, '\\'))) - namepart++; - else - namepart = filename; + if(!namepart) namepart = strrchr(filename, '\\'); + if(!namepart) namepart = filename; + else namepart++; + printf("Loading: %s (%s, %dhz, %" PRId64 " samples / %.2f seconds)\n", namepart, FormatName(format), sfinfo.samplerate, sfinfo.frames, (double)sfinfo.frames / sfinfo.samplerate); @@ -557,10 +557,9 @@ int main(int argc, char **argv) continue; namepart = strrchr(argv[i], '/'); - if(namepart || (namepart=strrchr(argv[i], '\\'))) - namepart++; - else - namepart = argv[i]; + if(!namepart) namepart = strrchr(argv[i], '\\'); + if(!namepart) namepart = argv[i]; + else namepart++; printf("Playing: %s (%s, %dhz)\n", namepart, FormatName(player->format), player->sfinfo.samplerate); diff --git a/examples/alffplay.cpp b/examples/alffplay.cpp index a7633bfa..cfbe5564 100644 --- a/examples/alffplay.cpp +++ b/examples/alffplay.cpp @@ -1297,7 +1297,7 @@ int AudioState::handler() mSamplesLen = decodeFrame(); mSamplesPos = mSamplesLen; } while(mSamplesLen > 0); - goto finish; + break; } ALenum state; @@ -1378,7 +1378,6 @@ int AudioState::handler() mSrcCond.wait_for(srclock, sleep_time); } -finish: alSourceRewind(mSource); alSourcei(mSource, AL_BUFFER, 0); diff --git a/examples/almultireverb.c b/examples/almultireverb.c index d1deae5a..f9a46c4f 100644 --- a/examples/almultireverb.c +++ b/examples/almultireverb.c @@ -108,7 +108,8 @@ static int LoadEffect(ALuint effect, const EFXEAXREVERBPROPERTIES *reverb) * the needed panning vectors). */ alEffecti(effect, AL_EFFECT_TYPE, AL_EFFECT_EAXREVERB); - if((err=alGetError()) != AL_NO_ERROR) + err = alGetError(); + if(err != AL_NO_ERROR) { fprintf(stderr, "Failed to set EAX Reverb: %s (0x%04x)\n", alGetString(err), err); return 0; @@ -140,7 +141,8 @@ static int LoadEffect(ALuint effect, const EFXEAXREVERBPROPERTIES *reverb) alEffecti(effect, AL_EAXREVERB_DECAY_HFLIMIT, reverb->iDecayHFLimit); /* Check if an error occurred, and return failure if so. */ - if((err=alGetError()) != AL_NO_ERROR) + err = alGetError(); + if(err != AL_NO_ERROR) { fprintf(stderr, "Error setting up reverb: %s\n", alGetString(err)); return 0; diff --git a/examples/alstream.c b/examples/alstream.c index c781f3d7..028290f5 100644 --- a/examples/alstream.c +++ b/examples/alstream.c @@ -294,7 +294,7 @@ static int OpenPlayerFile(StreamPlayer *player, const char *filename) player->block_count = player->sfinfo.samplerate / player->sampleblockalign; player->block_count = player->block_count * BufferMillisec / 1000; - player->membuf = malloc((size_t)(player->block_count * player->byteblockalign)); + player->membuf = malloc((size_t)player->block_count * (size_t)player->byteblockalign); return 1; } @@ -488,10 +488,9 @@ int main(int argc, char **argv) /* Get the name portion, without the path, for display. */ namepart = strrchr(argv[i], '/'); - if(namepart || (namepart=strrchr(argv[i], '\\'))) - namepart++; - else - namepart = argv[i]; + if(!namepart) namepart = strrchr(argv[i], '\\'); + if(!namepart) namepart = argv[i]; + else namepart++; printf("Playing: %s (%s, %dhz)\n", namepart, FormatName(player->format), player->sfinfo.samplerate); diff --git a/examples/alstreamcb.cpp b/examples/alstreamcb.cpp index 2da33b21..ebf3d3b0 100644 --- a/examples/alstreamcb.cpp +++ b/examples/alstreamcb.cpp @@ -195,12 +195,12 @@ struct StreamPlayer { if(mSampleFormat == SampleType::Int16) { mSamplesPerBlock = 1; - mBytesPerBlock = static_cast(mSfInfo.channels * 2); + mBytesPerBlock = static_cast(mSfInfo.channels) * 2; } else if(mSampleFormat == SampleType::Float) { mSamplesPerBlock = 1; - mBytesPerBlock = static_cast(mSfInfo.channels * 4); + mBytesPerBlock = static_cast(mSfInfo.channels) * 4; } else { diff --git a/utils/makemhr/loaddef.cpp b/utils/makemhr/loaddef.cpp index b33dbc75..05bcfd2e 100644 --- a/utils/makemhr/loaddef.cpp +++ b/utils/makemhr/loaddef.cpp @@ -907,7 +907,8 @@ static int ReadWaveList(std::istream &istream, const SourceRefT *src, const Byte fprintf(stderr, "\nError: Bad read from file '%s'.\n", src->mPath.data()); return 0; } - istream.seekg(static_cast(src->mOffset * block), std::ios::cur); + using off_type = std::istream::off_type; + istream.seekg(off_type(src->mOffset) * off_type(block), std::ios::cur); if(!ReadWaveData(istream, src, order, n, &hrir[0])) return 0; return 1; @@ -939,7 +940,8 @@ static int ReadWaveList(std::istream &istream, const SourceRefT *src, const Byte count = chunkSize / block; if(count > skip) { - istream.seekg(static_cast(skip * block), std::ios::cur); + using off_type = std::istream::off_type; + istream.seekg(off_type(skip) * off_type(block), std::ios::cur); chunkSize -= skip * block; count -= skip; skip = 0; -- cgit v1.2.3 From 18349e1da2c79d0f41c8c4f12ccd065f91618a6f Mon Sep 17 00:00:00 2001 From: Chris Robinson Date: Wed, 3 Jan 2024 14:58:07 -0800 Subject: Avoid using bit_cast for pointer types --- al/buffer.cpp | 2 +- al/state.cpp | 4 ++-- alc/alc.cpp | 2 +- alc/backends/alsa.cpp | 18 ++++++------------ alc/backends/dsound.cpp | 2 +- alc/backends/jack.cpp | 20 +++++++------------- alc/backends/pipewire.cpp | 8 ++++---- alc/backends/portaudio.cpp | 9 ++++----- alc/backends/pulseaudio.cpp | 13 ++++--------- common/dynload.cpp | 7 +++---- core/dbus_wrap.cpp | 18 +++++++++--------- 11 files changed, 42 insertions(+), 61 deletions(-) (limited to 'alc/backends/pulseaudio.cpp') diff --git a/al/buffer.cpp b/al/buffer.cpp index 2aafbf2d..b7ed5b32 100644 --- a/al/buffer.cpp +++ b/al/buffer.cpp @@ -1373,7 +1373,7 @@ FORCE_ALIGN void AL_APIENTRY alGetBufferPtrDirectSOFT(ALCcontext *context, ALuin else switch(param) { case AL_BUFFER_CALLBACK_FUNCTION_SOFT: - *value = al::bit_cast(albuf->mCallback); + *value = reinterpret_cast(albuf->mCallback); break; case AL_BUFFER_CALLBACK_USER_PARAM_SOFT: *value = albuf->mUserData; diff --git a/al/state.cpp b/al/state.cpp index c1e3d593..3ef87fbb 100644 --- a/al/state.cpp +++ b/al/state.cpp @@ -463,7 +463,7 @@ FORCE_ALIGN void AL_APIENTRY alGetPointervDirectSOFT(ALCcontext *context, ALenum switch(pname) { case AL_EVENT_CALLBACK_FUNCTION_SOFT: - *values = al::bit_cast(context->mEventCb); + *values = reinterpret_cast(context->mEventCb); break; case AL_EVENT_CALLBACK_USER_PARAM_SOFT: @@ -471,7 +471,7 @@ FORCE_ALIGN void AL_APIENTRY alGetPointervDirectSOFT(ALCcontext *context, ALenum break; case AL_DEBUG_CALLBACK_FUNCTION_EXT: - *values = al::bit_cast(context->mDebugCb); + *values = reinterpret_cast(context->mDebugCb); break; case AL_DEBUG_CALLBACK_USER_PARAM_EXT: diff --git a/alc/alc.cpp b/alc/alc.cpp index e5f2c545..b63317e7 100644 --- a/alc/alc.cpp +++ b/alc/alc.cpp @@ -174,7 +174,7 @@ BOOL APIENTRY DllMain(HINSTANCE module, DWORD reason, LPVOID /*reserved*/) case DLL_PROCESS_ATTACH: /* Pin the DLL so we won't get unloaded until the process terminates */ GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_PIN | GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, - al::bit_cast(module), &module); + reinterpret_cast(module), &module); break; } return TRUE; diff --git a/alc/backends/alsa.cpp b/alc/backends/alsa.cpp index d7dd16c0..4bda5b02 100644 --- a/alc/backends/alsa.cpp +++ b/alc/backends/alsa.cpp @@ -1196,13 +1196,9 @@ ClockLatency AlsaCapture::getClockLatency() bool AlsaBackendFactory::init() { - bool error{false}; - #ifdef HAVE_DYNLOAD if(!alsa_handle) { - std::string missing_funcs; - alsa_handle = LoadLib("libasound.so.2"); if(!alsa_handle) { @@ -1210,27 +1206,25 @@ bool AlsaBackendFactory::init() return false; } - error = false; + std::string missing_funcs; #define LOAD_FUNC(f) do { \ - p##f = al::bit_cast(GetSymbol(alsa_handle, #f)); \ - if(p##f == nullptr) { \ - error = true; \ - missing_funcs += "\n" #f; \ - } \ + p##f = reinterpret_cast(GetSymbol(alsa_handle, #f)); \ + if(p##f == nullptr) missing_funcs += "\n" #f; \ } while(0) ALSA_FUNCS(LOAD_FUNC); #undef LOAD_FUNC - if(error) + if(!missing_funcs.empty()) { WARN("Missing expected functions:%s\n", missing_funcs.c_str()); CloseLib(alsa_handle); alsa_handle = nullptr; + return false; } } #endif - return !error; + return true; } bool AlsaBackendFactory::querySupport(BackendType type) diff --git a/alc/backends/dsound.cpp b/alc/backends/dsound.cpp index 59a59a9f..e51c7ab5 100644 --- a/alc/backends/dsound.cpp +++ b/alc/backends/dsound.cpp @@ -774,7 +774,7 @@ bool DSoundBackendFactory::init() } #define LOAD_FUNC(f) do { \ - p##f = al::bit_cast(GetSymbol(ds_handle, #f)); \ + p##f = reinterpret_cast(GetSymbol(ds_handle, #f)); \ if(!p##f) \ { \ CloseLib(ds_handle); \ diff --git a/alc/backends/jack.cpp b/alc/backends/jack.cpp index 922873b8..1e5c17ad 100644 --- a/alc/backends/jack.cpp +++ b/alc/backends/jack.cpp @@ -109,13 +109,9 @@ jack_options_t ClientOptions = JackNullOption; bool jack_load() { - bool error{false}; - #ifdef HAVE_DYNLOAD if(!jack_handle) { - std::string missing_funcs; - #ifdef _WIN32 #define JACKLIB "libjack.dll" #else @@ -128,31 +124,29 @@ bool jack_load() return false; } - error = false; + std::string missing_funcs; #define LOAD_FUNC(f) do { \ - p##f = al::bit_cast(GetSymbol(jack_handle, #f)); \ - if(p##f == nullptr) { \ - error = true; \ - missing_funcs += "\n" #f; \ - } \ + p##f = reinterpret_cast(GetSymbol(jack_handle, #f)); \ + if(p##f == nullptr) missing_funcs += "\n" #f; \ } while(0) JACK_FUNCS(LOAD_FUNC); #undef LOAD_FUNC /* Optional symbols. These don't exist in all versions of JACK. */ -#define LOAD_SYM(f) p##f = al::bit_cast(GetSymbol(jack_handle, #f)) +#define LOAD_SYM(f) p##f = reinterpret_cast(GetSymbol(jack_handle, #f)) LOAD_SYM(jack_error_callback); #undef LOAD_SYM - if(error) + if(!missing_funcs.empty()) { WARN("Missing expected functions:%s\n", missing_funcs.c_str()); CloseLib(jack_handle); jack_handle = nullptr; + return false; } } #endif - return !error; + return true; } diff --git a/alc/backends/pipewire.cpp b/alc/backends/pipewire.cpp index c31f943e..55bcf6f4 100644 --- a/alc/backends/pipewire.cpp +++ b/alc/backends/pipewire.cpp @@ -256,7 +256,7 @@ bool pwire_load() } #define LOAD_FUNC(f) do { \ - p##f = al::bit_cast(GetSymbol(pwire_handle, #f)); \ + p##f = reinterpret_cast(GetSymbol(pwire_handle, #f)); \ if(p##f == nullptr) missing_funcs += "\n" #f; \ } while(0); PWIRE_FUNCS(LOAD_FUNC) @@ -374,11 +374,11 @@ To as(From) noexcept = delete; * - pw_metadata */ template<> -pw_proxy* as(pw_registry *reg) noexcept { return al::bit_cast(reg); } +pw_proxy* as(pw_registry *reg) noexcept { return reinterpret_cast(reg); } template<> -pw_proxy* as(pw_node *node) noexcept { return al::bit_cast(node); } +pw_proxy* as(pw_node *node) noexcept { return reinterpret_cast(node); } template<> -pw_proxy* as(pw_metadata *mdata) noexcept { return al::bit_cast(mdata); } +pw_proxy* as(pw_metadata *mdata) noexcept { return reinterpret_cast(mdata); } struct PwContextDeleter { diff --git a/alc/backends/portaudio.cpp b/alc/backends/portaudio.cpp index a8bd00fd..7c61e134 100644 --- a/alc/backends/portaudio.cpp +++ b/alc/backends/portaudio.cpp @@ -349,8 +349,6 @@ void PortCapture::captureSamples(std::byte *buffer, uint samples) bool PortBackendFactory::init() { - PaError err; - #ifdef HAVE_DYNLOAD if(!pa_handle) { @@ -369,7 +367,7 @@ bool PortBackendFactory::init() return false; #define LOAD_FUNC(f) do { \ - p##f = al::bit_cast(GetSymbol(pa_handle, #f)); \ + p##f = reinterpret_cast(GetSymbol(pa_handle, #f)); \ if(p##f == nullptr) \ { \ CloseLib(pa_handle); \ @@ -389,7 +387,7 @@ bool PortBackendFactory::init() LOAD_FUNC(Pa_GetStreamInfo); #undef LOAD_FUNC - err = Pa_Initialize(); + const PaError err{Pa_Initialize()}; if(err != paNoError) { ERR("Pa_Initialize() returned an error: %s\n", Pa_GetErrorText(err)); @@ -399,7 +397,8 @@ bool PortBackendFactory::init() } } #else - if((err=Pa_Initialize()) != paNoError) + const PaError err{Pa_Initialize()}; + if(err != paNoError) { ERR("Pa_Initialize() returned an error: %s\n", Pa_GetErrorText(err)); return false; diff --git a/alc/backends/pulseaudio.cpp b/alc/backends/pulseaudio.cpp index 77d45466..e976fc27 100644 --- a/alc/backends/pulseaudio.cpp +++ b/alc/backends/pulseaudio.cpp @@ -1389,9 +1389,6 @@ bool PulseBackendFactory::init() #ifdef HAVE_DYNLOAD if(!pulse_handle) { - bool ret{true}; - std::string missing_funcs; - #ifdef _WIN32 #define PALIB "libpulse-0.dll" #elif defined(__APPLE__) && defined(__MACH__) @@ -1406,17 +1403,15 @@ bool PulseBackendFactory::init() return false; } + std::string missing_funcs; #define LOAD_FUNC(x) do { \ - p##x = al::bit_cast(GetSymbol(pulse_handle, #x)); \ - if(!(p##x)) { \ - ret = false; \ - missing_funcs += "\n" #x; \ - } \ + p##x = reinterpret_cast(GetSymbol(pulse_handle, #x)); \ + if(!(p##x)) missing_funcs += "\n" #x; \ } while(0) PULSE_FUNCS(LOAD_FUNC) #undef LOAD_FUNC - if(!ret) + if(!missing_funcs.empty()) { WARN("Missing expected functions:%s\n", missing_funcs.c_str()); CloseLib(pulse_handle); diff --git a/common/dynload.cpp b/common/dynload.cpp index 86c36e00..333a9435 100644 --- a/common/dynload.cpp +++ b/common/dynload.cpp @@ -3,13 +3,12 @@ #include "dynload.h" -#include "albit.h" -#include "strutils.h" - #ifdef _WIN32 #define WIN32_LEAN_AND_MEAN #include +#include "strutils.h" + void *LoadLib(const char *name) { std::wstring wname{utf8_to_wstr(name)}; @@ -18,7 +17,7 @@ void *LoadLib(const char *name) void CloseLib(void *handle) { FreeLibrary(static_cast(handle)); } void *GetSymbol(void *handle, const char *name) -{ return al::bit_cast(GetProcAddress(static_cast(handle), name)); } +{ return reinterpret_cast(GetProcAddress(static_cast(handle), name)); } #elif defined(HAVE_DLFCN_H) diff --git a/core/dbus_wrap.cpp b/core/dbus_wrap.cpp index 08020c9b..05d9fc06 100644 --- a/core/dbus_wrap.cpp +++ b/core/dbus_wrap.cpp @@ -8,7 +8,6 @@ #include #include -#include "albit.h" #include "logging.h" @@ -16,8 +15,15 @@ void PrepareDBus() { const char *libname{"libdbus-1.so.3"}; + dbus_handle = LoadLib(libname); + if(!dbus_handle) + { + WARN("Failed to load %s\n", libname); + return; + } + auto load_func = [](auto &f, const char *name) -> void - { f = al::bit_cast>(GetSymbol(dbus_handle, name)); }; + { f = reinterpret_cast>(GetSymbol(dbus_handle, name)); }; #define LOAD_FUNC(x) do { \ load_func(p##x, #x); \ if(!p##x) \ @@ -29,14 +35,8 @@ void PrepareDBus() } \ } while(0); - dbus_handle = LoadLib(libname); - if(!dbus_handle) - { - WARN("Failed to load %s\n", libname); - return; - } + DBUS_FUNCTIONS(LOAD_FUNC) -DBUS_FUNCTIONS(LOAD_FUNC) #undef LOAD_FUNC } #endif -- cgit v1.2.3