From cb3e96e75640730b9391f0d2d922eecd9ee2ce79 Mon Sep 17 00:00:00 2001 From: Chris Robinson Date: Sun, 28 Jul 2019 18:56:04 -0700 Subject: Rename Alc to alc --- alc/backends/alsa.cpp | 1288 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 1288 insertions(+) create mode 100644 alc/backends/alsa.cpp (limited to 'alc/backends/alsa.cpp') diff --git a/alc/backends/alsa.cpp b/alc/backends/alsa.cpp new file mode 100644 index 00000000..c133df68 --- /dev/null +++ b/alc/backends/alsa.cpp @@ -0,0 +1,1288 @@ +/** + * OpenAL cross platform audio library + * Copyright (C) 1999-2007 by authors. + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public + * License along with this library; if not, write to the + * Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + * Or go to http://www.gnu.org/copyleft/lgpl.html + */ + +#include "config.h" + +#include "backends/alsa.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "AL/al.h" + +#include "albyte.h" +#include "alcmain.h" +#include "alconfig.h" +#include "almalloc.h" +#include "alnumeric.h" +#include "aloptional.h" +#include "alu.h" +#include "compat.h" +#include "logging.h" +#include "ringbuffer.h" +#include "threads.h" +#include "vector.h" + +#include + + +namespace { + +constexpr ALCchar alsaDevice[] = "ALSA Default"; + + +#ifdef HAVE_DYNLOAD +#define ALSA_FUNCS(MAGIC) \ + MAGIC(snd_strerror); \ + MAGIC(snd_pcm_open); \ + MAGIC(snd_pcm_close); \ + MAGIC(snd_pcm_nonblock); \ + MAGIC(snd_pcm_frames_to_bytes); \ + MAGIC(snd_pcm_bytes_to_frames); \ + MAGIC(snd_pcm_hw_params_malloc); \ + MAGIC(snd_pcm_hw_params_free); \ + MAGIC(snd_pcm_hw_params_any); \ + MAGIC(snd_pcm_hw_params_current); \ + MAGIC(snd_pcm_hw_params_set_access); \ + MAGIC(snd_pcm_hw_params_set_format); \ + MAGIC(snd_pcm_hw_params_set_channels); \ + MAGIC(snd_pcm_hw_params_set_periods_near); \ + MAGIC(snd_pcm_hw_params_set_rate_near); \ + MAGIC(snd_pcm_hw_params_set_rate); \ + MAGIC(snd_pcm_hw_params_set_rate_resample); \ + MAGIC(snd_pcm_hw_params_set_buffer_time_near); \ + MAGIC(snd_pcm_hw_params_set_period_time_near); \ + MAGIC(snd_pcm_hw_params_set_buffer_size_near); \ + MAGIC(snd_pcm_hw_params_set_period_size_near); \ + MAGIC(snd_pcm_hw_params_set_buffer_size_min); \ + MAGIC(snd_pcm_hw_params_get_buffer_time_min); \ + MAGIC(snd_pcm_hw_params_get_buffer_time_max); \ + MAGIC(snd_pcm_hw_params_get_period_time_min); \ + MAGIC(snd_pcm_hw_params_get_period_time_max); \ + MAGIC(snd_pcm_hw_params_get_buffer_size); \ + MAGIC(snd_pcm_hw_params_get_period_size); \ + MAGIC(snd_pcm_hw_params_get_access); \ + MAGIC(snd_pcm_hw_params_get_periods); \ + MAGIC(snd_pcm_hw_params_test_format); \ + MAGIC(snd_pcm_hw_params_test_channels); \ + MAGIC(snd_pcm_hw_params); \ + MAGIC(snd_pcm_sw_params_malloc); \ + MAGIC(snd_pcm_sw_params_current); \ + MAGIC(snd_pcm_sw_params_set_avail_min); \ + MAGIC(snd_pcm_sw_params_set_stop_threshold); \ + MAGIC(snd_pcm_sw_params); \ + MAGIC(snd_pcm_sw_params_free); \ + MAGIC(snd_pcm_prepare); \ + MAGIC(snd_pcm_start); \ + MAGIC(snd_pcm_resume); \ + MAGIC(snd_pcm_reset); \ + MAGIC(snd_pcm_wait); \ + MAGIC(snd_pcm_delay); \ + MAGIC(snd_pcm_state); \ + MAGIC(snd_pcm_avail_update); \ + MAGIC(snd_pcm_areas_silence); \ + MAGIC(snd_pcm_mmap_begin); \ + MAGIC(snd_pcm_mmap_commit); \ + MAGIC(snd_pcm_readi); \ + MAGIC(snd_pcm_writei); \ + MAGIC(snd_pcm_drain); \ + MAGIC(snd_pcm_drop); \ + MAGIC(snd_pcm_recover); \ + MAGIC(snd_pcm_info_malloc); \ + MAGIC(snd_pcm_info_free); \ + MAGIC(snd_pcm_info_set_device); \ + MAGIC(snd_pcm_info_set_subdevice); \ + MAGIC(snd_pcm_info_set_stream); \ + MAGIC(snd_pcm_info_get_name); \ + MAGIC(snd_ctl_pcm_next_device); \ + MAGIC(snd_ctl_pcm_info); \ + MAGIC(snd_ctl_open); \ + MAGIC(snd_ctl_close); \ + MAGIC(snd_ctl_card_info_malloc); \ + MAGIC(snd_ctl_card_info_free); \ + MAGIC(snd_ctl_card_info); \ + MAGIC(snd_ctl_card_info_get_name); \ + MAGIC(snd_ctl_card_info_get_id); \ + MAGIC(snd_card_next); \ + MAGIC(snd_config_update_free_global) + +static void *alsa_handle; +#define MAKE_FUNC(f) decltype(f) * p##f +ALSA_FUNCS(MAKE_FUNC); +#undef MAKE_FUNC + +#ifndef IN_IDE_PARSER +#define snd_strerror psnd_strerror +#define snd_pcm_open psnd_pcm_open +#define snd_pcm_close psnd_pcm_close +#define snd_pcm_nonblock psnd_pcm_nonblock +#define snd_pcm_frames_to_bytes psnd_pcm_frames_to_bytes +#define snd_pcm_bytes_to_frames psnd_pcm_bytes_to_frames +#define snd_pcm_hw_params_malloc psnd_pcm_hw_params_malloc +#define snd_pcm_hw_params_free psnd_pcm_hw_params_free +#define snd_pcm_hw_params_any psnd_pcm_hw_params_any +#define snd_pcm_hw_params_current psnd_pcm_hw_params_current +#define snd_pcm_hw_params_set_access psnd_pcm_hw_params_set_access +#define snd_pcm_hw_params_set_format psnd_pcm_hw_params_set_format +#define snd_pcm_hw_params_set_channels psnd_pcm_hw_params_set_channels +#define snd_pcm_hw_params_set_periods_near psnd_pcm_hw_params_set_periods_near +#define snd_pcm_hw_params_set_rate_near psnd_pcm_hw_params_set_rate_near +#define snd_pcm_hw_params_set_rate psnd_pcm_hw_params_set_rate +#define snd_pcm_hw_params_set_rate_resample psnd_pcm_hw_params_set_rate_resample +#define snd_pcm_hw_params_set_buffer_time_near psnd_pcm_hw_params_set_buffer_time_near +#define snd_pcm_hw_params_set_period_time_near psnd_pcm_hw_params_set_period_time_near +#define snd_pcm_hw_params_set_buffer_size_near psnd_pcm_hw_params_set_buffer_size_near +#define snd_pcm_hw_params_set_period_size_near psnd_pcm_hw_params_set_period_size_near +#define snd_pcm_hw_params_set_buffer_size_min psnd_pcm_hw_params_set_buffer_size_min +#define snd_pcm_hw_params_get_buffer_time_min psnd_pcm_hw_params_get_buffer_time_min +#define snd_pcm_hw_params_get_buffer_time_max psnd_pcm_hw_params_get_buffer_time_max +#define snd_pcm_hw_params_get_period_time_min psnd_pcm_hw_params_get_period_time_min +#define snd_pcm_hw_params_get_period_time_max psnd_pcm_hw_params_get_period_time_max +#define snd_pcm_hw_params_get_buffer_size psnd_pcm_hw_params_get_buffer_size +#define snd_pcm_hw_params_get_period_size psnd_pcm_hw_params_get_period_size +#define snd_pcm_hw_params_get_access psnd_pcm_hw_params_get_access +#define snd_pcm_hw_params_get_periods psnd_pcm_hw_params_get_periods +#define snd_pcm_hw_params_test_format psnd_pcm_hw_params_test_format +#define snd_pcm_hw_params_test_channels psnd_pcm_hw_params_test_channels +#define snd_pcm_hw_params psnd_pcm_hw_params +#define snd_pcm_sw_params_malloc psnd_pcm_sw_params_malloc +#define snd_pcm_sw_params_current psnd_pcm_sw_params_current +#define snd_pcm_sw_params_set_avail_min psnd_pcm_sw_params_set_avail_min +#define snd_pcm_sw_params_set_stop_threshold psnd_pcm_sw_params_set_stop_threshold +#define snd_pcm_sw_params psnd_pcm_sw_params +#define snd_pcm_sw_params_free psnd_pcm_sw_params_free +#define snd_pcm_prepare psnd_pcm_prepare +#define snd_pcm_start psnd_pcm_start +#define snd_pcm_resume psnd_pcm_resume +#define snd_pcm_reset psnd_pcm_reset +#define snd_pcm_wait psnd_pcm_wait +#define snd_pcm_delay psnd_pcm_delay +#define snd_pcm_state psnd_pcm_state +#define snd_pcm_avail_update psnd_pcm_avail_update +#define snd_pcm_areas_silence psnd_pcm_areas_silence +#define snd_pcm_mmap_begin psnd_pcm_mmap_begin +#define snd_pcm_mmap_commit psnd_pcm_mmap_commit +#define snd_pcm_readi psnd_pcm_readi +#define snd_pcm_writei psnd_pcm_writei +#define snd_pcm_drain psnd_pcm_drain +#define snd_pcm_drop psnd_pcm_drop +#define snd_pcm_recover psnd_pcm_recover +#define snd_pcm_info_malloc psnd_pcm_info_malloc +#define snd_pcm_info_free psnd_pcm_info_free +#define snd_pcm_info_set_device psnd_pcm_info_set_device +#define snd_pcm_info_set_subdevice psnd_pcm_info_set_subdevice +#define snd_pcm_info_set_stream psnd_pcm_info_set_stream +#define snd_pcm_info_get_name psnd_pcm_info_get_name +#define snd_ctl_pcm_next_device psnd_ctl_pcm_next_device +#define snd_ctl_pcm_info psnd_ctl_pcm_info +#define snd_ctl_open psnd_ctl_open +#define snd_ctl_close psnd_ctl_close +#define snd_ctl_card_info_malloc psnd_ctl_card_info_malloc +#define snd_ctl_card_info_free psnd_ctl_card_info_free +#define snd_ctl_card_info psnd_ctl_card_info +#define snd_ctl_card_info_get_name psnd_ctl_card_info_get_name +#define snd_ctl_card_info_get_id psnd_ctl_card_info_get_id +#define snd_card_next psnd_card_next +#define snd_config_update_free_global psnd_config_update_free_global +#endif +#endif + + +struct DevMap { + std::string name; + std::string device_name; +}; + +al::vector PlaybackDevices; +al::vector CaptureDevices; + + +const char *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"; +} + +al::vector probe_devices(snd_pcm_stream_t stream) +{ + al::vector devlist; + + snd_ctl_card_info_t *info; + snd_ctl_card_info_malloc(&info); + snd_pcm_info_t *pcminfo; + snd_pcm_info_malloc(&pcminfo); + + devlist.emplace_back(DevMap{alsaDevice, + GetConfigValue(nullptr, "alsa", (stream==SND_PCM_STREAM_PLAYBACK) ? "device" : "capture", + "default")}); + + if(stream == SND_PCM_STREAM_PLAYBACK) + { + const char *customdevs; + const char *next{GetConfigValue(nullptr, "alsa", "custom-devices", "")}; + while((customdevs=next) != nullptr && customdevs[0]) + { + next = strchr(customdevs, ';'); + const char *sep{strchr(customdevs, '=')}; + if(!sep) + { + std::string spec{next ? std::string(customdevs, next++) : std::string(customdevs)}; + ERR("Invalid ALSA device specification \"%s\"\n", spec.c_str()); + continue; + } + + const char *oldsep{sep++}; + devlist.emplace_back(DevMap{std::string(customdevs, oldsep), + next ? std::string(sep, next++) : std::string(sep)}); + const auto &entry = devlist.back(); + TRACE("Got device \"%s\", \"%s\"\n", entry.name.c_str(), entry.device_name.c_str()); + } + } + + const std::string main_prefix{ + ConfigValueStr(nullptr, "alsa", prefix_name(stream)).value_or("plughw:")}; + + int card{-1}; + int err{snd_card_next(&card)}; + for(;err >= 0 && card >= 0;err = snd_card_next(&card)) + { + std::string name{"hw:" + std::to_string(card)}; + + snd_ctl_t *handle; + if((err=snd_ctl_open(&handle, name.c_str(), 0)) < 0) + { + ERR("control open (hw:%d): %s\n", card, snd_strerror(err)); + continue; + } + if((err=snd_ctl_card_info(handle, info)) < 0) + { + ERR("control hardware info (hw:%d): %s\n", card, snd_strerror(err)); + snd_ctl_close(handle); + continue; + } + + const char *cardname{snd_ctl_card_info_get_name(info)}; + const char *cardid{snd_ctl_card_info_get_id(info)}; + name = prefix_name(stream); + name += '-'; + name += cardid; + const std::string card_prefix{ + ConfigValueStr(nullptr, "alsa", name.c_str()).value_or(main_prefix)}; + + int dev{-1}; + while(1) + { + if(snd_ctl_pcm_next_device(handle, &dev) < 0) + ERR("snd_ctl_pcm_next_device failed\n"); + if(dev < 0) break; + + snd_pcm_info_set_device(pcminfo, dev); + snd_pcm_info_set_subdevice(pcminfo, 0); + snd_pcm_info_set_stream(pcminfo, stream); + if((err=snd_ctl_pcm_info(handle, pcminfo)) < 0) + { + if(err != -ENOENT) + ERR("control digital audio info (hw:%d): %s\n", card, snd_strerror(err)); + continue; + } + + /* "prefix-cardid-dev" */ + name = prefix_name(stream); + name += '-'; + name += cardid; + name += '-'; + name += std::to_string(dev); + const std::string device_prefix{ + ConfigValueStr(nullptr, "alsa", name.c_str()).value_or(card_prefix)}; + + /* "CardName, PcmName (CARD=cardid,DEV=dev)" */ + name = cardname; + name += ", "; + name += snd_pcm_info_get_name(pcminfo); + name += " (CARD="; + name += cardid; + name += ",DEV="; + name += std::to_string(dev); + name += ')'; + + /* "devprefixCARD=cardid,DEV=dev" */ + std::string device{device_prefix}; + device += "CARD="; + device += cardid; + device += ",DEV="; + device += std::to_string(dev); + + devlist.emplace_back(DevMap{std::move(name), std::move(device)}); + const auto &entry = devlist.back(); + TRACE("Got device \"%s\", \"%s\"\n", entry.name.c_str(), entry.device_name.c_str()); + } + snd_ctl_close(handle); + } + if(err < 0) + ERR("snd_card_next failed: %s\n", snd_strerror(err)); + + snd_pcm_info_free(pcminfo); + snd_ctl_card_info_free(info); + + return devlist; +} + + +int verify_state(snd_pcm_t *handle) +{ + snd_pcm_state_t state{snd_pcm_state(handle)}; + + int err; + switch(state) + { + case SND_PCM_STATE_OPEN: + case SND_PCM_STATE_SETUP: + case SND_PCM_STATE_PREPARED: + case SND_PCM_STATE_RUNNING: + case SND_PCM_STATE_DRAINING: + case SND_PCM_STATE_PAUSED: + /* All Okay */ + break; + + case SND_PCM_STATE_XRUN: + if((err=snd_pcm_recover(handle, -EPIPE, 1)) < 0) + return err; + break; + case SND_PCM_STATE_SUSPENDED: + if((err=snd_pcm_recover(handle, -ESTRPIPE, 1)) < 0) + return err; + break; + case SND_PCM_STATE_DISCONNECTED: + return -ENODEV; + } + + return state; +} + + +struct AlsaPlayback final : public BackendBase { + AlsaPlayback(ALCdevice *device) noexcept : BackendBase{device} { } + ~AlsaPlayback() override; + + int mixerProc(); + int mixerNoMMapProc(); + + ALCenum open(const ALCchar *name) override; + ALCboolean reset() override; + ALCboolean start() override; + void stop() override; + + ClockLatency getClockLatency() override; + + snd_pcm_t *mPcmHandle{nullptr}; + + al::vector mBuffer; + + std::atomic mKillNow{true}; + std::thread mThread; + + DEF_NEWDEL(AlsaPlayback) +}; + +AlsaPlayback::~AlsaPlayback() +{ + if(mPcmHandle) + snd_pcm_close(mPcmHandle); + mPcmHandle = nullptr; +} + + +int AlsaPlayback::mixerProc() +{ + SetRTPriority(); + althrd_setname(MIXER_THREAD_NAME); + + const snd_pcm_uframes_t update_size{mDevice->UpdateSize}; + const snd_pcm_uframes_t num_updates{mDevice->BufferSize / update_size}; + while(!mKillNow.load(std::memory_order_acquire)) + { + int state{verify_state(mPcmHandle)}; + if(state < 0) + { + ERR("Invalid state detected: %s\n", snd_strerror(state)); + aluHandleDisconnect(mDevice, "Bad state: %s", snd_strerror(state)); + break; + } + + snd_pcm_sframes_t avail{snd_pcm_avail_update(mPcmHandle)}; + if(avail < 0) + { + ERR("available update failed: %s\n", snd_strerror(avail)); + continue; + } + + if(static_cast(avail) > update_size*(num_updates+1)) + { + WARN("available samples exceeds the buffer size\n"); + snd_pcm_reset(mPcmHandle); + continue; + } + + // make sure there's frames to process + if(static_cast(avail) < update_size) + { + if(state != SND_PCM_STATE_RUNNING) + { + int err{snd_pcm_start(mPcmHandle)}; + if(err < 0) + { + ERR("start failed: %s\n", snd_strerror(err)); + continue; + } + } + if(snd_pcm_wait(mPcmHandle, 1000) == 0) + ERR("Wait timeout... buffer size too low?\n"); + continue; + } + avail -= avail%update_size; + + // it is possible that contiguous areas are smaller, thus we use a loop + lock(); + while(avail > 0) + { + snd_pcm_uframes_t frames{static_cast(avail)}; + + const snd_pcm_channel_area_t *areas{}; + snd_pcm_uframes_t offset{}; + int err{snd_pcm_mmap_begin(mPcmHandle, &areas, &offset, &frames)}; + if(err < 0) + { + ERR("mmap begin error: %s\n", snd_strerror(err)); + break; + } + + char *WritePtr{static_cast(areas->addr) + (offset * areas->step / 8)}; + aluMixData(mDevice, WritePtr, frames); + + snd_pcm_sframes_t commitres{snd_pcm_mmap_commit(mPcmHandle, offset, frames)}; + if(commitres < 0 || (commitres-frames) != 0) + { + ERR("mmap commit error: %s\n", + snd_strerror(commitres >= 0 ? -EPIPE : commitres)); + break; + } + + avail -= frames; + } + unlock(); + } + + return 0; +} + +int AlsaPlayback::mixerNoMMapProc() +{ + SetRTPriority(); + althrd_setname(MIXER_THREAD_NAME); + + const snd_pcm_uframes_t update_size{mDevice->UpdateSize}; + const snd_pcm_uframes_t buffer_size{mDevice->BufferSize}; + while(!mKillNow.load(std::memory_order_acquire)) + { + int state{verify_state(mPcmHandle)}; + if(state < 0) + { + ERR("Invalid state detected: %s\n", snd_strerror(state)); + aluHandleDisconnect(mDevice, "Bad state: %s", snd_strerror(state)); + break; + } + + snd_pcm_sframes_t avail{snd_pcm_avail_update(mPcmHandle)}; + if(avail < 0) + { + ERR("available update failed: %s\n", snd_strerror(avail)); + continue; + } + + if(static_cast(avail) > buffer_size) + { + WARN("available samples exceeds the buffer size\n"); + snd_pcm_reset(mPcmHandle); + continue; + } + + if(static_cast(avail) < update_size) + { + if(state != SND_PCM_STATE_RUNNING) + { + int err{snd_pcm_start(mPcmHandle)}; + if(err < 0) + { + ERR("start failed: %s\n", snd_strerror(err)); + continue; + } + } + if(snd_pcm_wait(mPcmHandle, 1000) == 0) + ERR("Wait timeout... buffer size too low?\n"); + continue; + } + + lock(); + char *WritePtr{mBuffer.data()}; + avail = snd_pcm_bytes_to_frames(mPcmHandle, mBuffer.size()); + aluMixData(mDevice, WritePtr, avail); + while(avail > 0) + { + snd_pcm_sframes_t ret{snd_pcm_writei(mPcmHandle, WritePtr, avail)}; + switch(ret) + { + case -EAGAIN: + continue; +#if ESTRPIPE != EPIPE + case -ESTRPIPE: +#endif + case -EPIPE: + case -EINTR: + ret = snd_pcm_recover(mPcmHandle, ret, 1); + if(ret < 0) + avail = 0; + break; + default: + if(ret >= 0) + { + WritePtr += snd_pcm_frames_to_bytes(mPcmHandle, ret); + avail -= ret; + } + break; + } + if(ret < 0) + { + ret = snd_pcm_prepare(mPcmHandle); + if(ret < 0) break; + } + } + unlock(); + } + + return 0; +} + + +ALCenum AlsaPlayback::open(const ALCchar *name) +{ + const char *driver{}; + if(name) + { + if(PlaybackDevices.empty()) + PlaybackDevices = probe_devices(SND_PCM_STREAM_PLAYBACK); + + auto iter = std::find_if(PlaybackDevices.cbegin(), PlaybackDevices.cend(), + [name](const DevMap &entry) -> bool + { return entry.name == name; } + ); + if(iter == PlaybackDevices.cend()) + return ALC_INVALID_VALUE; + driver = iter->device_name.c_str(); + } + else + { + name = alsaDevice; + driver = GetConfigValue(nullptr, "alsa", "device", "default"); + } + + TRACE("Opening device \"%s\"\n", driver); + int err{snd_pcm_open(&mPcmHandle, driver, SND_PCM_STREAM_PLAYBACK, SND_PCM_NONBLOCK)}; + if(err < 0) + { + ERR("Could not open playback device '%s': %s\n", driver, snd_strerror(err)); + return ALC_OUT_OF_MEMORY; + } + + /* Free alsa's global config tree. Otherwise valgrind reports a ton of leaks. */ + snd_config_update_free_global(); + + mDevice->DeviceName = name; + + return ALC_NO_ERROR; +} + +ALCboolean AlsaPlayback::reset() +{ + snd_pcm_format_t format{SND_PCM_FORMAT_UNKNOWN}; + switch(mDevice->FmtType) + { + case DevFmtByte: + format = SND_PCM_FORMAT_S8; + break; + case DevFmtUByte: + format = SND_PCM_FORMAT_U8; + break; + case DevFmtShort: + format = SND_PCM_FORMAT_S16; + break; + case DevFmtUShort: + format = SND_PCM_FORMAT_U16; + break; + case DevFmtInt: + format = SND_PCM_FORMAT_S32; + break; + case DevFmtUInt: + format = SND_PCM_FORMAT_U32; + break; + case DevFmtFloat: + format = SND_PCM_FORMAT_FLOAT; + break; + } + + bool allowmmap{!!GetConfigValueBool(mDevice->DeviceName.c_str(), "alsa", "mmap", 1)}; + ALuint periodLen{static_cast(mDevice->UpdateSize * 1000000_u64 / mDevice->Frequency)}; + ALuint bufferLen{static_cast(mDevice->BufferSize * 1000000_u64 / mDevice->Frequency)}; + ALuint rate{mDevice->Frequency}; + + snd_pcm_uframes_t periodSizeInFrames{}; + snd_pcm_uframes_t bufferSizeInFrames{}; + snd_pcm_sw_params_t *sp{}; + snd_pcm_hw_params_t *hp{}; + snd_pcm_access_t access{}; + const char *funcerr{}; + int err{}; + + snd_pcm_hw_params_malloc(&hp); +#define CHECK(x) if((funcerr=#x),(err=(x)) < 0) goto error + CHECK(snd_pcm_hw_params_any(mPcmHandle, hp)); + /* set interleaved access */ + if(!allowmmap || snd_pcm_hw_params_set_access(mPcmHandle, hp, SND_PCM_ACCESS_MMAP_INTERLEAVED) < 0) + { + /* No mmap */ + CHECK(snd_pcm_hw_params_set_access(mPcmHandle, hp, SND_PCM_ACCESS_RW_INTERLEAVED)); + } + /* test and set format (implicitly sets sample bits) */ + if(snd_pcm_hw_params_test_format(mPcmHandle, hp, format) < 0) + { + static const struct { + 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 }, + }; + + for(const auto &fmt : formatlist) + { + format = fmt.format; + if(snd_pcm_hw_params_test_format(mPcmHandle, hp, format) >= 0) + { + mDevice->FmtType = fmt.fmttype; + break; + } + } + } + CHECK(snd_pcm_hw_params_set_format(mPcmHandle, hp, format)); + /* test and set channels (implicitly sets frame bits) */ + if(snd_pcm_hw_params_test_channels(mPcmHandle, hp, mDevice->channelsFromFmt()) < 0) + { + static const DevFmtChannels channellist[] = { + DevFmtStereo, + DevFmtQuad, + DevFmtX51, + DevFmtX71, + DevFmtMono, + }; + + for(const auto &chan : channellist) + { + if(snd_pcm_hw_params_test_channels(mPcmHandle, hp, ChannelsFromDevFmt(chan, 0)) >= 0) + { + mDevice->FmtChans = chan; + mDevice->mAmbiOrder = 0; + break; + } + } + } + CHECK(snd_pcm_hw_params_set_channels(mPcmHandle, hp, mDevice->channelsFromFmt())); + /* set rate (implicitly constrains period/buffer parameters) */ + if(!GetConfigValueBool(mDevice->DeviceName.c_str(), "alsa", "allow-resampler", 0) || + !mDevice->Flags.get()) + { + if(snd_pcm_hw_params_set_rate_resample(mPcmHandle, hp, 0) < 0) + ERR("Failed to disable ALSA resampler\n"); + } + else if(snd_pcm_hw_params_set_rate_resample(mPcmHandle, hp, 1) < 0) + ERR("Failed to enable ALSA resampler\n"); + CHECK(snd_pcm_hw_params_set_rate_near(mPcmHandle, hp, &rate, nullptr)); + /* set period time (implicitly constrains period/buffer parameters) */ + if((err=snd_pcm_hw_params_set_period_time_near(mPcmHandle, hp, &periodLen, nullptr)) < 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, &bufferLen, nullptr)) < 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)); + + /* retrieve configuration info */ + CHECK(snd_pcm_hw_params_get_access(hp, &access)); + CHECK(snd_pcm_hw_params_get_period_size(hp, &periodSizeInFrames, nullptr)); + CHECK(snd_pcm_hw_params_get_buffer_size(hp, &bufferSizeInFrames)); + snd_pcm_hw_params_free(hp); + hp = nullptr; + + snd_pcm_sw_params_malloc(&sp); + CHECK(snd_pcm_sw_params_current(mPcmHandle, sp)); + CHECK(snd_pcm_sw_params_set_avail_min(mPcmHandle, sp, periodSizeInFrames)); + CHECK(snd_pcm_sw_params_set_stop_threshold(mPcmHandle, sp, bufferSizeInFrames)); + CHECK(snd_pcm_sw_params(mPcmHandle, sp)); +#undef CHECK + snd_pcm_sw_params_free(sp); + sp = nullptr; + + mDevice->BufferSize = bufferSizeInFrames; + mDevice->UpdateSize = periodSizeInFrames; + mDevice->Frequency = rate; + + SetDefaultChannelOrder(mDevice); + + return ALC_TRUE; + +error: + ERR("%s failed: %s\n", funcerr, snd_strerror(err)); + if(hp) snd_pcm_hw_params_free(hp); + if(sp) snd_pcm_sw_params_free(sp); + return ALC_FALSE; +} + +ALCboolean AlsaPlayback::start() +{ + snd_pcm_hw_params_t *hp{}; + snd_pcm_access_t access; + const char *funcerr; + int err; + + snd_pcm_hw_params_malloc(&hp); +#define CHECK(x) if((funcerr=#x),(err=(x)) < 0) goto error + CHECK(snd_pcm_hw_params_current(mPcmHandle, hp)); + /* retrieve configuration info */ + CHECK(snd_pcm_hw_params_get_access(hp, &access)); +#undef CHECK + if(0) + { + error: + ERR("%s failed: %s\n", funcerr, snd_strerror(err)); + if(hp) snd_pcm_hw_params_free(hp); + return ALC_FALSE; + } + snd_pcm_hw_params_free(hp); + hp = nullptr; + + int (AlsaPlayback::*thread_func)(){}; + if(access == SND_PCM_ACCESS_RW_INTERLEAVED) + { + mBuffer.resize(snd_pcm_frames_to_bytes(mPcmHandle, mDevice->UpdateSize)); + thread_func = &AlsaPlayback::mixerNoMMapProc; + } + else + { + err = snd_pcm_prepare(mPcmHandle); + if(err < 0) + { + ERR("snd_pcm_prepare(data->mPcmHandle) failed: %s\n", snd_strerror(err)); + return ALC_FALSE; + } + thread_func = &AlsaPlayback::mixerProc; + } + + try { + mKillNow.store(false, std::memory_order_release); + mThread = std::thread{std::mem_fn(thread_func), this}; + return ALC_TRUE; + } + catch(std::exception& e) { + ERR("Could not create playback thread: %s\n", e.what()); + } + catch(...) { + } + mBuffer.clear(); + return ALC_FALSE; +} + +void AlsaPlayback::stop() +{ + if(mKillNow.exchange(true, std::memory_order_acq_rel) || !mThread.joinable()) + return; + mThread.join(); + + mBuffer.clear(); +} + +ClockLatency AlsaPlayback::getClockLatency() +{ + ClockLatency ret; + + lock(); + ret.ClockTime = GetDeviceClockTime(mDevice); + snd_pcm_sframes_t delay{}; + int err{snd_pcm_delay(mPcmHandle, &delay)}; + if(err < 0) + { + ERR("Failed to get pcm delay: %s\n", snd_strerror(err)); + delay = 0; + } + ret.Latency = std::chrono::seconds{std::max(0, delay)}; + ret.Latency /= mDevice->Frequency; + unlock(); + + return ret; +} + + +struct AlsaCapture final : public BackendBase { + AlsaCapture(ALCdevice *device) noexcept : BackendBase{device} { } + ~AlsaCapture() override; + + ALCenum open(const ALCchar *name) override; + ALCboolean start() override; + void stop() override; + ALCenum captureSamples(ALCvoid *buffer, ALCuint samples) override; + ALCuint availableSamples() override; + ClockLatency getClockLatency() override; + + snd_pcm_t *mPcmHandle{nullptr}; + + al::vector mBuffer; + + bool mDoCapture{false}; + RingBufferPtr mRing{nullptr}; + + snd_pcm_sframes_t mLastAvail{0}; + + DEF_NEWDEL(AlsaCapture) +}; + +AlsaCapture::~AlsaCapture() +{ + if(mPcmHandle) + snd_pcm_close(mPcmHandle); + mPcmHandle = nullptr; +} + + +ALCenum AlsaCapture::open(const ALCchar *name) +{ + const char *driver{}; + if(name) + { + if(CaptureDevices.empty()) + CaptureDevices = probe_devices(SND_PCM_STREAM_CAPTURE); + + auto iter = std::find_if(CaptureDevices.cbegin(), CaptureDevices.cend(), + [name](const DevMap &entry) -> bool + { return entry.name == name; } + ); + if(iter == CaptureDevices.cend()) + return ALC_INVALID_VALUE; + driver = iter->device_name.c_str(); + } + else + { + name = alsaDevice; + driver = GetConfigValue(nullptr, "alsa", "capture", "default"); + } + + TRACE("Opening device \"%s\"\n", driver); + int err{snd_pcm_open(&mPcmHandle, driver, SND_PCM_STREAM_CAPTURE, SND_PCM_NONBLOCK)}; + if(err < 0) + { + ERR("Could not open capture device '%s': %s\n", driver, snd_strerror(err)); + return ALC_INVALID_VALUE; + } + + /* Free alsa's global config tree. Otherwise valgrind reports a ton of leaks. */ + snd_config_update_free_global(); + + snd_pcm_format_t format{SND_PCM_FORMAT_UNKNOWN}; + switch(mDevice->FmtType) + { + case DevFmtByte: + format = SND_PCM_FORMAT_S8; + break; + case DevFmtUByte: + format = SND_PCM_FORMAT_U8; + break; + case DevFmtShort: + format = SND_PCM_FORMAT_S16; + break; + case DevFmtUShort: + format = SND_PCM_FORMAT_U16; + break; + case DevFmtInt: + format = SND_PCM_FORMAT_S32; + break; + case DevFmtUInt: + format = SND_PCM_FORMAT_U32; + break; + case DevFmtFloat: + format = SND_PCM_FORMAT_FLOAT; + break; + } + + snd_pcm_uframes_t bufferSizeInFrames{maxu(mDevice->BufferSize, 100*mDevice->Frequency/1000)}; + snd_pcm_uframes_t periodSizeInFrames{minu(bufferSizeInFrames, 25*mDevice->Frequency/1000)}; + + bool needring{false}; + const char *funcerr{}; + snd_pcm_hw_params_t *hp{}; + snd_pcm_hw_params_malloc(&hp); +#define CHECK(x) if((funcerr=#x),(err=(x)) < 0) goto error + CHECK(snd_pcm_hw_params_any(mPcmHandle, hp)); + /* set interleaved access */ + CHECK(snd_pcm_hw_params_set_access(mPcmHandle, hp, SND_PCM_ACCESS_RW_INTERLEAVED)); + /* set format (implicitly sets sample bits) */ + CHECK(snd_pcm_hw_params_set_format(mPcmHandle, hp, format)); + /* set channels (implicitly sets frame bits) */ + CHECK(snd_pcm_hw_params_set_channels(mPcmHandle, hp, mDevice->channelsFromFmt())); + /* set rate (implicitly constrains period/buffer parameters) */ + CHECK(snd_pcm_hw_params_set_rate(mPcmHandle, hp, mDevice->Frequency, 0)); + /* set buffer size in frame units (implicitly sets period size/bytes/time and buffer time/bytes) */ + if(snd_pcm_hw_params_set_buffer_size_min(mPcmHandle, hp, &bufferSizeInFrames) < 0) + { + TRACE("Buffer too large, using intermediate ring buffer\n"); + needring = true; + CHECK(snd_pcm_hw_params_set_buffer_size_near(mPcmHandle, hp, &bufferSizeInFrames)); + } + /* set buffer size in frame units (implicitly sets period size/bytes/time and buffer time/bytes) */ + CHECK(snd_pcm_hw_params_set_period_size_near(mPcmHandle, hp, &periodSizeInFrames, nullptr)); + /* install and prepare hardware configuration */ + CHECK(snd_pcm_hw_params(mPcmHandle, hp)); + /* retrieve configuration info */ + CHECK(snd_pcm_hw_params_get_period_size(hp, &periodSizeInFrames, nullptr)); +#undef CHECK + snd_pcm_hw_params_free(hp); + hp = nullptr; + + if(needring) + { + mRing = CreateRingBuffer(mDevice->BufferSize, mDevice->frameSizeFromFmt(), false); + if(!mRing) + { + ERR("ring buffer create failed\n"); + goto error2; + } + } + + mDevice->DeviceName = name; + + return ALC_NO_ERROR; + +error: + ERR("%s failed: %s\n", funcerr, snd_strerror(err)); + if(hp) snd_pcm_hw_params_free(hp); + +error2: + mRing = nullptr; + snd_pcm_close(mPcmHandle); + mPcmHandle = nullptr; + + return ALC_INVALID_VALUE; +} + + +ALCboolean AlsaCapture::start() +{ + int err{snd_pcm_prepare(mPcmHandle)}; + if(err < 0) + ERR("prepare failed: %s\n", snd_strerror(err)); + else + { + err = snd_pcm_start(mPcmHandle); + if(err < 0) + ERR("start failed: %s\n", snd_strerror(err)); + } + if(err < 0) + { + aluHandleDisconnect(mDevice, "Capture state failure: %s", snd_strerror(err)); + return ALC_FALSE; + } + + mDoCapture = true; + return ALC_TRUE; +} + +void AlsaCapture::stop() +{ + /* OpenAL requires access to unread audio after stopping, but ALSA's + * snd_pcm_drain is unreliable and snd_pcm_drop drops it. Capture what's + * available now so it'll be available later after the drop. + */ + ALCuint avail{availableSamples()}; + if(!mRing && avail > 0) + { + /* The ring buffer implicitly captures when checking availability. + * Direct access needs to explicitly capture it into temp storage. */ + al::vector temp(snd_pcm_frames_to_bytes(mPcmHandle, avail)); + captureSamples(temp.data(), avail); + mBuffer = std::move(temp); + } + int err{snd_pcm_drop(mPcmHandle)}; + if(err < 0) + ERR("drop failed: %s\n", snd_strerror(err)); + mDoCapture = false; +} + +ALCenum AlsaCapture::captureSamples(ALCvoid *buffer, ALCuint samples) +{ + if(mRing) + { + mRing->read(buffer, samples); + return ALC_NO_ERROR; + } + + mLastAvail -= samples; + while(mDevice->Connected.load(std::memory_order_acquire) && samples > 0) + { + snd_pcm_sframes_t amt{0}; + + if(!mBuffer.empty()) + { + /* First get any data stored from the last stop */ + amt = snd_pcm_bytes_to_frames(mPcmHandle, mBuffer.size()); + if(static_cast(amt) > samples) amt = samples; + + amt = snd_pcm_frames_to_bytes(mPcmHandle, amt); + memcpy(buffer, mBuffer.data(), amt); + + mBuffer.erase(mBuffer.begin(), mBuffer.begin()+amt); + amt = snd_pcm_bytes_to_frames(mPcmHandle, amt); + } + else if(mDoCapture) + amt = snd_pcm_readi(mPcmHandle, buffer, samples); + if(amt < 0) + { + ERR("read error: %s\n", snd_strerror(amt)); + + if(amt == -EAGAIN) + continue; + if((amt=snd_pcm_recover(mPcmHandle, amt, 1)) >= 0) + { + amt = snd_pcm_start(mPcmHandle); + if(amt >= 0) + amt = snd_pcm_avail_update(mPcmHandle); + } + if(amt < 0) + { + ERR("restore error: %s\n", snd_strerror(amt)); + aluHandleDisconnect(mDevice, "Capture recovery failure: %s", snd_strerror(amt)); + break; + } + /* If the amount available is less than what's asked, we lost it + * during recovery. So just give silence instead. */ + if(static_cast(amt) < samples) + break; + continue; + } + + buffer = static_cast(buffer) + amt; + samples -= amt; + } + if(samples > 0) + memset(buffer, ((mDevice->FmtType == DevFmtUByte) ? 0x80 : 0), + snd_pcm_frames_to_bytes(mPcmHandle, samples)); + + return ALC_NO_ERROR; +} + +ALCuint AlsaCapture::availableSamples() +{ + snd_pcm_sframes_t avail{0}; + if(mDevice->Connected.load(std::memory_order_acquire) && mDoCapture) + avail = snd_pcm_avail_update(mPcmHandle); + if(avail < 0) + { + ERR("avail update failed: %s\n", snd_strerror(avail)); + + if((avail=snd_pcm_recover(mPcmHandle, avail, 1)) >= 0) + { + if(mDoCapture) + avail = snd_pcm_start(mPcmHandle); + if(avail >= 0) + avail = snd_pcm_avail_update(mPcmHandle); + } + if(avail < 0) + { + ERR("restore error: %s\n", snd_strerror(avail)); + aluHandleDisconnect(mDevice, "Capture recovery failure: %s", snd_strerror(avail)); + } + } + + if(!mRing) + { + if(avail < 0) avail = 0; + avail += snd_pcm_bytes_to_frames(mPcmHandle, mBuffer.size()); + if(avail > mLastAvail) mLastAvail = avail; + return mLastAvail; + } + + while(avail > 0) + { + auto vec = mRing->getWriteVector(); + if(vec.first.len == 0) break; + + snd_pcm_sframes_t amt{std::min(vec.first.len, avail)}; + amt = snd_pcm_readi(mPcmHandle, vec.first.buf, amt); + if(amt < 0) + { + ERR("read error: %s\n", snd_strerror(amt)); + + if(amt == -EAGAIN) + continue; + if((amt=snd_pcm_recover(mPcmHandle, amt, 1)) >= 0) + { + if(mDoCapture) + amt = snd_pcm_start(mPcmHandle); + if(amt >= 0) + amt = snd_pcm_avail_update(mPcmHandle); + } + if(amt < 0) + { + ERR("restore error: %s\n", snd_strerror(amt)); + aluHandleDisconnect(mDevice, "Capture recovery failure: %s", snd_strerror(amt)); + break; + } + avail = amt; + continue; + } + + mRing->writeAdvance(amt); + avail -= amt; + } + + return mRing->readSpace(); +} + +ClockLatency AlsaCapture::getClockLatency() +{ + ClockLatency ret; + + lock(); + ret.ClockTime = GetDeviceClockTime(mDevice); + snd_pcm_sframes_t delay{}; + int err{snd_pcm_delay(mPcmHandle, &delay)}; + if(err < 0) + { + ERR("Failed to get pcm delay: %s\n", snd_strerror(err)); + delay = 0; + } + ret.Latency = std::chrono::seconds{std::max(0, delay)}; + ret.Latency /= mDevice->Frequency; + unlock(); + + return ret; +} + +} // namespace + + +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) + { + WARN("Failed to load %s\n", "libasound.so.2"); + return ALC_FALSE; + } + + error = ALC_FALSE; +#define LOAD_FUNC(f) do { \ + p##f = reinterpret_cast(GetSymbol(alsa_handle, #f)); \ + if(p##f == nullptr) { \ + error = true; \ + missing_funcs += "\n" #f; \ + } \ +} while(0) + ALSA_FUNCS(LOAD_FUNC); +#undef LOAD_FUNC + + if(error) + { + WARN("Missing expected functions:%s\n", missing_funcs.c_str()); + CloseLib(alsa_handle); + alsa_handle = nullptr; + } + } +#endif + + return !error; +} + +bool AlsaBackendFactory::querySupport(BackendType type) +{ return (type == BackendType::Playback || type == BackendType::Capture); } + +void AlsaBackendFactory::probe(DevProbe type, std::string *outnames) +{ + auto add_device = [outnames](const DevMap &entry) -> void + { + /* +1 to also append the null char (to ensure a null-separated list and + * double-null terminated list). + */ + outnames->append(entry.name.c_str(), entry.name.length()+1); + }; + switch(type) + { + case DevProbe::Playback: + PlaybackDevices = probe_devices(SND_PCM_STREAM_PLAYBACK); + std::for_each(PlaybackDevices.cbegin(), PlaybackDevices.cend(), add_device); + break; + + case DevProbe::Capture: + CaptureDevices = probe_devices(SND_PCM_STREAM_CAPTURE); + std::for_each(CaptureDevices.cbegin(), CaptureDevices.cend(), add_device); + break; + } +} + +BackendPtr AlsaBackendFactory::createBackend(ALCdevice *device, BackendType type) +{ + if(type == BackendType::Playback) + return BackendPtr{new AlsaPlayback{device}}; + if(type == BackendType::Capture) + return BackendPtr{new AlsaCapture{device}}; + return nullptr; +} + +BackendFactory &AlsaBackendFactory::getFactory() +{ + static AlsaBackendFactory factory{}; + return factory; +} -- cgit v1.2.3 From 70058a8a8405a36c66235a56b482c4c0c7a46780 Mon Sep 17 00:00:00 2001 From: Chris Robinson Date: Sat, 10 Aug 2019 21:54:30 -0700 Subject: Move the dynload decls and defs to common --- CMakeLists.txt | 2 ++ alc/backends/alsa.cpp | 2 +- alc/backends/dsound.cpp | 1 + alc/backends/jack.cpp | 2 +- alc/backends/portaudio.cpp | 2 +- alc/backends/pulseaudio.cpp | 3 ++- alc/compat.h | 16 ------------ alc/helpers.cpp | 45 -------------------------------- common/dynload.cpp | 62 +++++++++++++++++++++++++++++++++++++++++++++ common/dynload.h | 14 ++++++++++ 10 files changed, 84 insertions(+), 65 deletions(-) create mode 100644 common/dynload.cpp create mode 100644 common/dynload.h (limited to 'alc/backends/alsa.cpp') diff --git a/CMakeLists.txt b/CMakeLists.txt index 2fd0b69a..6fe05f35 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -598,6 +598,8 @@ SET(COMMON_OBJS common/aloptional.h common/alspan.h common/atomic.h + common/dynload.cpp + common/dynload.h common/endiantest.h common/intrusive_ptr.h common/math_defs.h diff --git a/alc/backends/alsa.cpp b/alc/backends/alsa.cpp index c133df68..64f9cf46 100644 --- a/alc/backends/alsa.cpp +++ b/alc/backends/alsa.cpp @@ -44,7 +44,7 @@ #include "alnumeric.h" #include "aloptional.h" #include "alu.h" -#include "compat.h" +#include "dynload.h" #include "logging.h" #include "ringbuffer.h" #include "threads.h" diff --git a/alc/backends/dsound.cpp b/alc/backends/dsound.cpp index 5a156d54..b9e52c0c 100644 --- a/alc/backends/dsound.cpp +++ b/alc/backends/dsound.cpp @@ -48,6 +48,7 @@ #include "alu.h" #include "ringbuffer.h" #include "compat.h" +#include "dynload.h" #include "threads.h" /* MinGW-w64 needs this for some unknown reason now. */ diff --git a/alc/backends/jack.cpp b/alc/backends/jack.cpp index 3f81d08c..e688b96b 100644 --- a/alc/backends/jack.cpp +++ b/alc/backends/jack.cpp @@ -32,9 +32,9 @@ #include "alcmain.h" #include "alu.h" #include "alconfig.h" +#include "dynload.h" #include "ringbuffer.h" #include "threads.h" -#include "compat.h" #include #include diff --git a/alc/backends/portaudio.cpp b/alc/backends/portaudio.cpp index 73e972c5..fcfd4b01 100644 --- a/alc/backends/portaudio.cpp +++ b/alc/backends/portaudio.cpp @@ -29,8 +29,8 @@ #include "alcmain.h" #include "alu.h" #include "alconfig.h" +#include "dynload.h" #include "ringbuffer.h" -#include "compat.h" #include diff --git a/alc/backends/pulseaudio.cpp b/alc/backends/pulseaudio.cpp index 2ddcc86d..ca2ecb43 100644 --- a/alc/backends/pulseaudio.cpp +++ b/alc/backends/pulseaudio.cpp @@ -37,8 +37,9 @@ #include "alcmain.h" #include "alu.h" #include "alconfig.h" -#include "compat.h" #include "alexcpt.h" +#include "compat.h" +#include "dynload.h" #include diff --git a/alc/compat.h b/alc/compat.h index 4ffc40bf..648fa5b1 100644 --- a/alc/compat.h +++ b/alc/compat.h @@ -1,8 +1,6 @@ #ifndef AL_COMPAT_H #define AL_COMPAT_H -#ifdef __cplusplus - #ifdef _WIN32 #define WIN32_LEAN_AND_MEAN @@ -86,8 +84,6 @@ public: } // namespace al -#define HAVE_DYNLOAD 1 - #else /* _WIN32 */ #include @@ -99,10 +95,6 @@ using ifstream = std::ifstream; } // namespace al -#if defined(HAVE_DLFCN_H) -#define HAVE_DYNLOAD 1 -#endif - #endif /* _WIN32 */ #include @@ -110,12 +102,4 @@ using ifstream = std::ifstream; struct PathNamePair { std::string path, fname; }; const PathNamePair &GetProcBinary(void); -#ifdef HAVE_DYNLOAD -void *LoadLib(const char *name); -void CloseLib(void *handle); -void *GetSymbol(void *handle, const char *name); -#endif - -#endif /* __cplusplus */ - #endif /* AL_COMPAT_H */ diff --git a/alc/helpers.cpp b/alc/helpers.cpp index d1401c3c..b952c5ed 100644 --- a/alc/helpers.cpp +++ b/alc/helpers.cpp @@ -81,9 +81,6 @@ DEFINE_PROPERTYKEY(PKEY_AudioEndpoint_GUID, 0x1da5d803, 0xd492, 0x4edd, 0x8c, 0x #endif #endif /* AL_NO_UID_DEFS */ -#ifdef HAVE_DLFCN_H -#include -#endif #ifdef HAVE_INTRIN_H #include #endif @@ -454,21 +451,6 @@ const PathNamePair &GetProcBinary() } -void *LoadLib(const char *name) -{ - std::wstring wname{utf8_to_wstr(name)}; - return LoadLibraryW(wname.c_str()); -} -void CloseLib(void *handle) -{ FreeLibrary(static_cast(handle)); } -void *GetSymbol(void *handle, const char *name) -{ - void *ret{reinterpret_cast(GetProcAddress(static_cast(handle), name))}; - if(!ret) ERR("Failed to load %s\n", name); - return ret; -} - - void al_print(FILE *logfile, const char *fmt, ...) { al::vector dynmsg; @@ -683,33 +665,6 @@ const PathNamePair &GetProcBinary() } -#ifdef HAVE_DLFCN_H - -void *LoadLib(const char *name) -{ - dlerror(); - void *handle{dlopen(name, RTLD_NOW)}; - const char *err{dlerror()}; - if(err) handle = nullptr; - return handle; -} -void CloseLib(void *handle) -{ dlclose(handle); } -void *GetSymbol(void *handle, const char *name) -{ - dlerror(); - void *sym{dlsym(handle, name)}; - const char *err{dlerror()}; - if(err) - { - WARN("Failed to load %s: %s\n", name, err); - sym = nullptr; - } - return sym; -} - -#endif /* HAVE_DLFCN_H */ - void al_print(FILE *logfile, const char *fmt, ...) { va_list ap; diff --git a/common/dynload.cpp b/common/dynload.cpp new file mode 100644 index 00000000..89824f78 --- /dev/null +++ b/common/dynload.cpp @@ -0,0 +1,62 @@ + +#include "config.h" + +#include "dynload.h" + + +#ifdef _WIN32 + +#define WIN32_LEAN_AND_MEAN +#include + +#include + +inline std::wstring utf8_to_wstr(const char *str) +{ + std::wstring ret; + + int len = MultiByteToWideChar(CP_UTF8, 0, str, -1, NULL, 0); + if(len > 0) + { + ret.resize(len); + MultiByteToWideChar(CP_UTF8, 0, str, -1, &ret[0], len); + ret.pop_back(); + } + + return ret; +} + +void *LoadLib(const char *name) +{ + std::wstring wname{utf8_to_wstr(name)}; + return LoadLibraryW(wname.c_str()); +} +void CloseLib(void *handle) +{ FreeLibrary(static_cast(handle)); } +void *GetSymbol(void *handle, const char *name) +{ return reinterpret_cast(GetProcAddress(static_cast(handle), name)); } + +#elif defined(HAVE_DLFCN_H) + +#include + +void *LoadLib(const char *name) +{ + dlerror(); + void *handle{dlopen(name, RTLD_NOW)}; + const char *err{dlerror()}; + if(err) handle = nullptr; + return handle; +} +void CloseLib(void *handle) +{ dlclose(handle); } +void *GetSymbol(void *handle, const char *name) +{ + dlerror(); + void *sym{dlsym(handle, name)}; + const char *err{dlerror()}; + if(err) sym = nullptr; + return sym; +} + +#endif diff --git a/common/dynload.h b/common/dynload.h new file mode 100644 index 00000000..bd9e86f7 --- /dev/null +++ b/common/dynload.h @@ -0,0 +1,14 @@ +#ifndef AL_DYNLOAD_H +#define AL_DYNLOAD_H + +#if defined(_WIN32) || defined(HAVE_DLFCN_H) + +#define HAVE_DYNLOAD + +void *LoadLib(const char *name); +void CloseLib(void *handle); +void *GetSymbol(void *handle, const char *name); + +#endif + +#endif /* AL_DYNLOAD_H */ -- cgit v1.2.3 From 4e72d7b3eccfb13055c55d2ccac8bf0db3be9ecb Mon Sep 17 00:00:00 2001 From: Chris Robinson Date: Sun, 25 Aug 2019 18:09:14 -0700 Subject: Use al::byte for a couple more buffers --- alc/backends/alsa.cpp | 10 +++++----- alc/backends/wave.cpp | 12 ++++++------ 2 files changed, 11 insertions(+), 11 deletions(-) (limited to 'alc/backends/alsa.cpp') diff --git a/alc/backends/alsa.cpp b/alc/backends/alsa.cpp index 64f9cf46..766ff167 100644 --- a/alc/backends/alsa.cpp +++ b/alc/backends/alsa.cpp @@ -403,7 +403,7 @@ struct AlsaPlayback final : public BackendBase { snd_pcm_t *mPcmHandle{nullptr}; - al::vector mBuffer; + al::vector mBuffer; std::atomic mKillNow{true}; std::thread mThread; @@ -550,7 +550,7 @@ int AlsaPlayback::mixerNoMMapProc() } lock(); - char *WritePtr{mBuffer.data()}; + al::byte *WritePtr{mBuffer.data()}; avail = snd_pcm_bytes_to_frames(mPcmHandle, mBuffer.size()); aluMixData(mDevice, WritePtr, avail); while(avail > 0) @@ -874,7 +874,7 @@ struct AlsaCapture final : public BackendBase { snd_pcm_t *mPcmHandle{nullptr}; - al::vector mBuffer; + al::vector mBuffer; bool mDoCapture{false}; RingBufferPtr mRing{nullptr}; @@ -1044,7 +1044,7 @@ void AlsaCapture::stop() { /* The ring buffer implicitly captures when checking availability. * Direct access needs to explicitly capture it into temp storage. */ - al::vector temp(snd_pcm_frames_to_bytes(mPcmHandle, avail)); + auto temp = al::vector(snd_pcm_frames_to_bytes(mPcmHandle, avail)); captureSamples(temp.data(), avail); mBuffer = std::move(temp); } @@ -1106,7 +1106,7 @@ ALCenum AlsaCapture::captureSamples(ALCvoid *buffer, ALCuint samples) continue; } - buffer = static_cast(buffer) + amt; + buffer = static_cast(buffer) + amt; samples -= amt; } if(samples > 0) diff --git a/alc/backends/wave.cpp b/alc/backends/wave.cpp index aa4130af..b16f711b 100644 --- a/alc/backends/wave.cpp +++ b/alc/backends/wave.cpp @@ -35,6 +35,7 @@ #include "AL/al.h" +#include "albyte.h" #include "alcmain.h" #include "alconfig.h" #include "almalloc.h" @@ -103,7 +104,7 @@ struct WaveBackend final : public BackendBase { FILE *mFile{nullptr}; long mDataStart{-1}; - al::vector mBuffer; + al::vector mBuffer; std::atomic mKillNow{true}; std::thread mThread; @@ -151,13 +152,12 @@ int WaveBackend::mixerProc() if(!IS_LITTLE_ENDIAN) { const ALsizei bytesize{mDevice->bytesFromFmt()}; - ALsizei i; if(bytesize == 2) { ALushort *samples = reinterpret_cast(mBuffer.data()); - const auto len = static_cast(mBuffer.size() / 2); - for(i = 0;i < len;i++) + const size_t len{mBuffer.size() / 2}; + for(size_t i{0};i < len;i++) { ALushort samp = samples[i]; samples[i] = (samp>>8) | (samp<<8); @@ -166,8 +166,8 @@ int WaveBackend::mixerProc() else if(bytesize == 4) { ALuint *samples = reinterpret_cast(mBuffer.data()); - const auto len = static_cast(mBuffer.size() / 4); - for(i = 0;i < len;i++) + const size_t len{mBuffer.size() / 4}; + for(size_t i{0};i < len;i++) { ALuint samp = samples[i]; samples[i] = (samp>>24) | ((samp>>8)&0x0000ff00) | -- cgit v1.2.3 From 532197a650729be5e4405fd64f81e4443090a01e Mon Sep 17 00:00:00 2001 From: Chris Robinson Date: Sat, 14 Sep 2019 12:44:35 -0700 Subject: Clean up (most) implicit conversions in the backends --- alc/backends/alsa.cpp | 93 ++++++++++++++++++++++++--------------------- alc/backends/dsound.cpp | 20 ++++++---- alc/backends/oss.cpp | 4 +- alc/backends/pulseaudio.cpp | 47 ++++++++++++----------- alc/backends/wasapi.cpp | 12 +++--- alc/backends/winmm.cpp | 8 ++-- 6 files changed, 98 insertions(+), 86 deletions(-) (limited to 'alc/backends/alsa.cpp') diff --git a/alc/backends/alsa.cpp b/alc/backends/alsa.cpp index 766ff167..cd85afaf 100644 --- a/alc/backends/alsa.cpp +++ b/alc/backends/alsa.cpp @@ -303,7 +303,7 @@ al::vector probe_devices(snd_pcm_stream_t stream) ERR("snd_ctl_pcm_next_device failed\n"); if(dev < 0) break; - snd_pcm_info_set_device(pcminfo, dev); + 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) @@ -425,7 +425,7 @@ int AlsaPlayback::mixerProc() althrd_setname(MIXER_THREAD_NAME); const snd_pcm_uframes_t update_size{mDevice->UpdateSize}; - const snd_pcm_uframes_t num_updates{mDevice->BufferSize / update_size}; + const snd_pcm_uframes_t buffer_size{mDevice->BufferSize}; while(!mKillNow.load(std::memory_order_acquire)) { int state{verify_state(mPcmHandle)}; @@ -436,14 +436,15 @@ int AlsaPlayback::mixerProc() break; } - snd_pcm_sframes_t avail{snd_pcm_avail_update(mPcmHandle)}; - if(avail < 0) + snd_pcm_sframes_t avails{snd_pcm_avail_update(mPcmHandle)}; + if(avails < 0) { - ERR("available update failed: %s\n", snd_strerror(avail)); + ERR("available update failed: %s\n", snd_strerror(static_cast(avails))); continue; } + snd_pcm_uframes_t avail{static_cast(avails)}; - if(static_cast(avail) > update_size*(num_updates+1)) + if(avail > buffer_size) { WARN("available samples exceeds the buffer size\n"); snd_pcm_reset(mPcmHandle); @@ -451,7 +452,7 @@ int AlsaPlayback::mixerProc() } // make sure there's frames to process - if(static_cast(avail) < update_size) + if(avail < update_size) { if(state != SND_PCM_STATE_RUNNING) { @@ -472,7 +473,7 @@ int AlsaPlayback::mixerProc() lock(); while(avail > 0) { - snd_pcm_uframes_t frames{static_cast(avail)}; + snd_pcm_uframes_t frames{avail}; const snd_pcm_channel_area_t *areas{}; snd_pcm_uframes_t offset{}; @@ -484,13 +485,13 @@ int AlsaPlayback::mixerProc() } char *WritePtr{static_cast(areas->addr) + (offset * areas->step / 8)}; - aluMixData(mDevice, WritePtr, frames); + aluMixData(mDevice, WritePtr, static_cast(frames)); snd_pcm_sframes_t commitres{snd_pcm_mmap_commit(mPcmHandle, offset, frames)}; - if(commitres < 0 || (commitres-frames) != 0) + if(commitres < 0 || (static_cast(commitres)-frames) != 0) { ERR("mmap commit error: %s\n", - snd_strerror(commitres >= 0 ? -EPIPE : commitres)); + snd_strerror(commitres >= 0 ? -EPIPE : static_cast(commitres))); break; } @@ -522,7 +523,7 @@ int AlsaPlayback::mixerNoMMapProc() snd_pcm_sframes_t avail{snd_pcm_avail_update(mPcmHandle)}; if(avail < 0) { - ERR("available update failed: %s\n", snd_strerror(avail)); + ERR("available update failed: %s\n", snd_strerror(static_cast(avail))); continue; } @@ -551,11 +552,12 @@ int AlsaPlayback::mixerNoMMapProc() lock(); al::byte *WritePtr{mBuffer.data()}; - avail = snd_pcm_bytes_to_frames(mPcmHandle, mBuffer.size()); - aluMixData(mDevice, WritePtr, avail); + avail = snd_pcm_bytes_to_frames(mPcmHandle, static_cast(mBuffer.size())); + aluMixData(mDevice, WritePtr, static_cast(avail)); while(avail > 0) { - snd_pcm_sframes_t ret{snd_pcm_writei(mPcmHandle, WritePtr, avail)}; + snd_pcm_sframes_t ret{snd_pcm_writei(mPcmHandle, WritePtr, + static_cast(avail))}; switch(ret) { case -EAGAIN: @@ -565,7 +567,7 @@ int AlsaPlayback::mixerNoMMapProc() #endif case -EPIPE: case -EINTR: - ret = snd_pcm_recover(mPcmHandle, ret, 1); + ret = snd_pcm_recover(mPcmHandle, static_cast(ret), 1); if(ret < 0) avail = 0; break; @@ -762,8 +764,8 @@ ALCboolean AlsaPlayback::reset() snd_pcm_sw_params_free(sp); sp = nullptr; - mDevice->BufferSize = bufferSizeInFrames; - mDevice->UpdateSize = periodSizeInFrames; + mDevice->BufferSize = static_cast(bufferSizeInFrames); + mDevice->UpdateSize = static_cast(periodSizeInFrames); mDevice->Frequency = rate; SetDefaultChannelOrder(mDevice); @@ -803,7 +805,8 @@ ALCboolean AlsaPlayback::start() int (AlsaPlayback::*thread_func)(){}; if(access == SND_PCM_ACCESS_RW_INTERLEAVED) { - mBuffer.resize(snd_pcm_frames_to_bytes(mPcmHandle, mDevice->UpdateSize)); + mBuffer.resize( + static_cast(snd_pcm_frames_to_bytes(mPcmHandle, mDevice->UpdateSize))); thread_func = &AlsaPlayback::mixerNoMMapProc; } else @@ -952,7 +955,7 @@ ALCenum AlsaCapture::open(const ALCchar *name) } snd_pcm_uframes_t bufferSizeInFrames{maxu(mDevice->BufferSize, 100*mDevice->Frequency/1000)}; - snd_pcm_uframes_t periodSizeInFrames{minu(bufferSizeInFrames, 25*mDevice->Frequency/1000)}; + snd_pcm_uframes_t periodSizeInFrames{minu(mDevice->BufferSize, 25*mDevice->Frequency/1000)}; bool needring{false}; const char *funcerr{}; @@ -1044,7 +1047,8 @@ void AlsaCapture::stop() { /* The ring buffer implicitly captures when checking availability. * Direct access needs to explicitly capture it into temp storage. */ - auto temp = al::vector(snd_pcm_frames_to_bytes(mPcmHandle, avail)); + auto temp = al::vector( + static_cast(snd_pcm_frames_to_bytes(mPcmHandle, avail))); captureSamples(temp.data(), avail); mBuffer = std::move(temp); } @@ -1070,11 +1074,11 @@ ALCenum AlsaCapture::captureSamples(ALCvoid *buffer, ALCuint samples) if(!mBuffer.empty()) { /* First get any data stored from the last stop */ - amt = snd_pcm_bytes_to_frames(mPcmHandle, mBuffer.size()); + amt = snd_pcm_bytes_to_frames(mPcmHandle, static_cast(mBuffer.size())); if(static_cast(amt) > samples) amt = samples; amt = snd_pcm_frames_to_bytes(mPcmHandle, amt); - memcpy(buffer, mBuffer.data(), amt); + std::copy_n(mBuffer.begin(), amt, static_cast(buffer)); mBuffer.erase(mBuffer.begin(), mBuffer.begin()+amt); amt = snd_pcm_bytes_to_frames(mPcmHandle, amt); @@ -1083,11 +1087,11 @@ ALCenum AlsaCapture::captureSamples(ALCvoid *buffer, ALCuint samples) amt = snd_pcm_readi(mPcmHandle, buffer, samples); if(amt < 0) { - ERR("read error: %s\n", snd_strerror(amt)); + ERR("read error: %s\n", snd_strerror(static_cast(amt))); if(amt == -EAGAIN) continue; - if((amt=snd_pcm_recover(mPcmHandle, amt, 1)) >= 0) + if((amt=snd_pcm_recover(mPcmHandle, static_cast(amt), 1)) >= 0) { amt = snd_pcm_start(mPcmHandle); if(amt >= 0) @@ -1095,8 +1099,9 @@ ALCenum AlsaCapture::captureSamples(ALCvoid *buffer, ALCuint samples) } if(amt < 0) { - ERR("restore error: %s\n", snd_strerror(amt)); - aluHandleDisconnect(mDevice, "Capture recovery failure: %s", snd_strerror(amt)); + const char *err{snd_strerror(static_cast(amt))}; + ERR("restore error: %s\n", err); + aluHandleDisconnect(mDevice, "Capture recovery failure: %s", err); break; } /* If the amount available is less than what's asked, we lost it @@ -1110,8 +1115,8 @@ ALCenum AlsaCapture::captureSamples(ALCvoid *buffer, ALCuint samples) samples -= amt; } if(samples > 0) - memset(buffer, ((mDevice->FmtType == DevFmtUByte) ? 0x80 : 0), - snd_pcm_frames_to_bytes(mPcmHandle, samples)); + std::fill_n(static_cast(buffer), snd_pcm_frames_to_bytes(mPcmHandle, samples), + al::byte((mDevice->FmtType == DevFmtUByte) ? 0x80 : 0)); return ALC_NO_ERROR; } @@ -1123,9 +1128,9 @@ ALCuint AlsaCapture::availableSamples() avail = snd_pcm_avail_update(mPcmHandle); if(avail < 0) { - ERR("avail update failed: %s\n", snd_strerror(avail)); + ERR("avail update failed: %s\n", snd_strerror(static_cast(avail))); - if((avail=snd_pcm_recover(mPcmHandle, avail, 1)) >= 0) + if((avail=snd_pcm_recover(mPcmHandle, static_cast(avail), 1)) >= 0) { if(mDoCapture) avail = snd_pcm_start(mPcmHandle); @@ -1134,17 +1139,18 @@ ALCuint AlsaCapture::availableSamples() } if(avail < 0) { - ERR("restore error: %s\n", snd_strerror(avail)); - aluHandleDisconnect(mDevice, "Capture recovery failure: %s", snd_strerror(avail)); + const char *err{snd_strerror(static_cast(avail))}; + ERR("restore error: %s\n", err); + aluHandleDisconnect(mDevice, "Capture recovery failure: %s", err); } } if(!mRing) { if(avail < 0) avail = 0; - avail += snd_pcm_bytes_to_frames(mPcmHandle, mBuffer.size()); + avail += snd_pcm_bytes_to_frames(mPcmHandle, static_cast(mBuffer.size())); if(avail > mLastAvail) mLastAvail = avail; - return mLastAvail; + return static_cast(mLastAvail); } while(avail > 0) @@ -1152,15 +1158,15 @@ ALCuint AlsaCapture::availableSamples() auto vec = mRing->getWriteVector(); if(vec.first.len == 0) break; - snd_pcm_sframes_t amt{std::min(vec.first.len, avail)}; - amt = snd_pcm_readi(mPcmHandle, vec.first.buf, amt); + snd_pcm_sframes_t amt{std::min(static_cast(vec.first.len), avail)}; + amt = snd_pcm_readi(mPcmHandle, vec.first.buf, static_cast(amt)); if(amt < 0) { - ERR("read error: %s\n", snd_strerror(amt)); + ERR("read error: %s\n", snd_strerror(static_cast(amt))); if(amt == -EAGAIN) continue; - if((amt=snd_pcm_recover(mPcmHandle, amt, 1)) >= 0) + if((amt=snd_pcm_recover(mPcmHandle, static_cast(amt), 1)) >= 0) { if(mDoCapture) amt = snd_pcm_start(mPcmHandle); @@ -1169,19 +1175,20 @@ ALCuint AlsaCapture::availableSamples() } if(amt < 0) { - ERR("restore error: %s\n", snd_strerror(amt)); - aluHandleDisconnect(mDevice, "Capture recovery failure: %s", snd_strerror(amt)); + const char *err{snd_strerror(static_cast(amt))}; + ERR("restore error: %s\n", err); + aluHandleDisconnect(mDevice, "Capture recovery failure: %s", err); break; } avail = amt; continue; } - mRing->writeAdvance(amt); + mRing->writeAdvance(static_cast(amt)); avail -= amt; } - return mRing->readSpace(); + return static_cast(mRing->readSpace()); } ClockLatency AlsaCapture::getClockLatency() diff --git a/alc/backends/dsound.cpp b/alc/backends/dsound.cpp index 1c44c2ec..f9184968 100644 --- a/alc/backends/dsound.cpp +++ b/alc/backends/dsound.cpp @@ -465,11 +465,13 @@ ALCboolean DSoundPlayback::reset() retry_open: hr = S_OK; OutputType.Format.wFormatTag = WAVE_FORMAT_PCM; - OutputType.Format.nChannels = mDevice->channelsFromFmt(); - OutputType.Format.wBitsPerSample = mDevice->bytesFromFmt() * 8; - OutputType.Format.nBlockAlign = OutputType.Format.nChannels*OutputType.Format.wBitsPerSample/8; + OutputType.Format.nChannels = static_cast(mDevice->channelsFromFmt()); + OutputType.Format.wBitsPerSample = static_cast(mDevice->bytesFromFmt() * 8); + OutputType.Format.nBlockAlign = static_cast(OutputType.Format.nChannels * + OutputType.Format.wBitsPerSample / 8); OutputType.Format.nSamplesPerSec = mDevice->Frequency; - OutputType.Format.nAvgBytesPerSec = OutputType.Format.nSamplesPerSec*OutputType.Format.nBlockAlign; + OutputType.Format.nAvgBytesPerSec = OutputType.Format.nSamplesPerSec * + OutputType.Format.nBlockAlign; OutputType.Format.cbSize = 0; } @@ -728,11 +730,13 @@ ALCenum DSoundCapture::open(const ALCchar *name) } InputType.Format.wFormatTag = WAVE_FORMAT_PCM; - InputType.Format.nChannels = mDevice->channelsFromFmt(); - InputType.Format.wBitsPerSample = mDevice->bytesFromFmt() * 8; - InputType.Format.nBlockAlign = InputType.Format.nChannels*InputType.Format.wBitsPerSample/8; + InputType.Format.nChannels = static_cast(mDevice->channelsFromFmt()); + InputType.Format.wBitsPerSample = static_cast(mDevice->bytesFromFmt() * 8); + InputType.Format.nBlockAlign = static_cast(InputType.Format.nChannels * + InputType.Format.wBitsPerSample / 8); InputType.Format.nSamplesPerSec = mDevice->Frequency; - InputType.Format.nAvgBytesPerSec = InputType.Format.nSamplesPerSec*InputType.Format.nBlockAlign; + InputType.Format.nAvgBytesPerSec = InputType.Format.nSamplesPerSec * + InputType.Format.nBlockAlign; InputType.Format.cbSize = 0; InputType.Samples.wValidBitsPerSample = InputType.Format.wBitsPerSample; if(mDevice->FmtType == DevFmtFloat) diff --git a/alc/backends/oss.cpp b/alc/backends/oss.cpp index 48794a50..ffdf3c23 100644 --- a/alc/backends/oss.cpp +++ b/alc/backends/oss.cpp @@ -305,7 +305,7 @@ int OSSPlayback::mixerProc() ALubyte *write_ptr{mMixData.data()}; size_t to_write{mMixData.size()}; - aluMixData(mDevice, write_ptr, to_write/frame_size); + aluMixData(mDevice, write_ptr, static_cast(to_write/frame_size)); while(to_write > 0 && !mKillNow.load(std::memory_order_acquire)) { ssize_t wrote{write(mFd, write_ptr, to_write)}; @@ -531,7 +531,7 @@ int OSScapture::recordProc() strerror(errno)); break; } - mRing->writeAdvance(amt/frame_size); + mRing->writeAdvance(static_cast(amt)/frame_size); } } diff --git a/alc/backends/pulseaudio.cpp b/alc/backends/pulseaudio.cpp index c1e615ae..08420748 100644 --- a/alc/backends/pulseaudio.cpp +++ b/alc/backends/pulseaudio.cpp @@ -743,7 +743,7 @@ void PulsePlayback::streamWriteCallbackC(pa_stream *stream, size_t nbytes, void void PulsePlayback::streamWriteCallback(pa_stream *stream, size_t nbytes) { void *buf{pa_xmalloc(nbytes)}; - aluMixData(mDevice, buf, nbytes/mFrameSize); + aluMixData(mDevice, buf, static_cast(nbytes/mFrameSize)); int ret{pa_stream_write(stream, buf, nbytes, pa_xfree, 0, PA_SEEK_RELATIVE)}; if UNLIKELY(ret != PA_OK) @@ -864,7 +864,7 @@ ALCenum PulsePlayback::open(const ALCchar *name) BackendType::Playback); pa_stream_set_moved_callback(mStream, &PulsePlayback::streamMovedCallbackC, this); - mFrameSize = pa_frame_size(pa_stream_get_sample_spec(mStream)); + mFrameSize = static_cast(pa_frame_size(pa_stream_get_sample_spec(mStream))); mDeviceName = pa_stream_get_device_name(mStream); if(!dev_name) @@ -970,15 +970,16 @@ ALCboolean PulsePlayback::reset() break; } mSpec.rate = mDevice->Frequency; - mSpec.channels = mDevice->channelsFromFmt(); + mSpec.channels = static_cast(mDevice->channelsFromFmt()); if(pa_sample_spec_valid(&mSpec) == 0) throw al::backend_exception{ALC_INVALID_VALUE, "Invalid sample spec"}; - mAttr.maxlength = -1; - mAttr.tlength = mDevice->BufferSize * pa_frame_size(&mSpec); - mAttr.prebuf = 0; - mAttr.minreq = mDevice->UpdateSize * pa_frame_size(&mSpec); - mAttr.fragsize = -1; + const ALuint frame_size{static_cast(pa_frame_size(&mSpec))}; + mAttr.maxlength = ~0u; + mAttr.tlength = mDevice->BufferSize * frame_size; + mAttr.prebuf = 0u; + mAttr.minreq = mDevice->UpdateSize * frame_size; + mAttr.fragsize = ~0u; mStream = pulse_connect_stream(mDeviceName.c_str(), plock, mContext, flags, &mAttr, &mSpec, &chanmap, BackendType::Playback); @@ -987,7 +988,7 @@ ALCboolean PulsePlayback::reset() pa_stream_set_moved_callback(mStream, &PulsePlayback::streamMovedCallbackC, this); mSpec = *(pa_stream_get_sample_spec(mStream)); - mFrameSize = pa_frame_size(&mSpec); + mFrameSize = static_cast(pa_frame_size(&mSpec)); if(mDevice->Frequency != mSpec.rate) { @@ -1000,9 +1001,9 @@ ALCboolean PulsePlayback::reset() const ALuint buflen{static_cast(clampd(scale*mDevice->BufferSize + 0.5, perlen*2, std::numeric_limits::max()/mFrameSize))}; - mAttr.maxlength = -1; + mAttr.maxlength = ~0u; mAttr.tlength = buflen * mFrameSize; - mAttr.prebuf = 0; + mAttr.prebuf = 0u; mAttr.minreq = perlen * mFrameSize; op = pa_stream_set_buffer_attr(mStream, &mAttr, stream_success_callback, nullptr); @@ -1268,18 +1269,17 @@ ALCenum PulseCapture::open(const ALCchar *name) DevFmtTypeString(mDevice->FmtType)}; } mSpec.rate = mDevice->Frequency; - mSpec.channels = mDevice->channelsFromFmt(); + mSpec.channels = static_cast(mDevice->channelsFromFmt()); if(pa_sample_spec_valid(&mSpec) == 0) throw al::backend_exception{ALC_INVALID_VALUE, "Invalid sample format"}; - ALuint samples{mDevice->BufferSize}; - samples = maxu(samples, 100 * mDevice->Frequency / 1000); - - mAttr.minreq = -1; - mAttr.prebuf = -1; - mAttr.maxlength = samples * pa_frame_size(&mSpec); - mAttr.tlength = -1; - mAttr.fragsize = minu(samples, 50*mDevice->Frequency/1000) * pa_frame_size(&mSpec); + const ALuint frame_size{static_cast(pa_frame_size(&mSpec))}; + const ALuint samples{maxu(mDevice->BufferSize, 100 * mDevice->Frequency / 1000)}; + mAttr.minreq = ~0u; + mAttr.prebuf = ~0u; + mAttr.maxlength = samples * frame_size; + mAttr.tlength = ~0u; + 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", 1)) @@ -1384,8 +1384,9 @@ ALCuint PulseCapture::availableSamples() size_t got{pa_stream_readable_size(mStream)}; if(static_cast(got) < 0) { - ERR("pa_stream_readable_size() failed: %s\n", pa_strerror(got)); - aluHandleDisconnect(mDevice, "Failed getting readable size: %s", pa_strerror(got)); + const char *err{pa_strerror(static_cast(got))}; + ERR("pa_stream_readable_size() failed: %s\n", err); + aluHandleDisconnect(mDevice, "Failed getting readable size: %s", err); } else { @@ -1396,7 +1397,7 @@ ALCuint PulseCapture::availableSamples() readable = std::min(readable, std::numeric_limits::max()); mLastReadable = std::max(mLastReadable, static_cast(readable)); - return mLastReadable / pa_frame_size(&mSpec); + return mLastReadable / static_cast(pa_frame_size(&mSpec)); } diff --git a/alc/backends/wasapi.cpp b/alc/backends/wasapi.cpp index 55c95146..b762da76 100644 --- a/alc/backends/wasapi.cpp +++ b/alc/backends/wasapi.cpp @@ -942,10 +942,10 @@ HRESULT WasapiPlayback::resetProxy() } OutputType.Format.nSamplesPerSec = mDevice->Frequency; - OutputType.Format.nBlockAlign = OutputType.Format.nChannels * - OutputType.Format.wBitsPerSample / 8; + OutputType.Format.nBlockAlign = static_cast(OutputType.Format.nChannels * + OutputType.Format.wBitsPerSample / 8); OutputType.Format.nAvgBytesPerSec = OutputType.Format.nSamplesPerSec * - OutputType.Format.nBlockAlign; + OutputType.Format.nBlockAlign; TraceFormat("Requesting playback format", &OutputType.Format); hr = mClient->IsFormatSupported(AUDCLNT_SHAREMODE_SHARED, &OutputType.Format, &wfx); @@ -1474,10 +1474,10 @@ HRESULT WasapiCapture::resetProxy() OutputType.Samples.wValidBitsPerSample = OutputType.Format.wBitsPerSample; OutputType.Format.nSamplesPerSec = mDevice->Frequency; - OutputType.Format.nBlockAlign = OutputType.Format.nChannels * - OutputType.Format.wBitsPerSample / 8; + OutputType.Format.nBlockAlign = static_cast(OutputType.Format.nChannels * + OutputType.Format.wBitsPerSample / 8); OutputType.Format.nAvgBytesPerSec = OutputType.Format.nSamplesPerSec * - OutputType.Format.nBlockAlign; + OutputType.Format.nBlockAlign; OutputType.Format.cbSize = sizeof(OutputType) - sizeof(OutputType.Format); TraceFormat("Requesting capture format", &OutputType.Format); diff --git a/alc/backends/winmm.cpp b/alc/backends/winmm.cpp index 76e6fe3b..30a19e13 100644 --- a/alc/backends/winmm.cpp +++ b/alc/backends/winmm.cpp @@ -240,7 +240,7 @@ retry_open: mFormat.wBitsPerSample = 16; } mFormat.nChannels = ((mDevice->FmtChans == DevFmtMono) ? 1 : 2); - mFormat.nBlockAlign = mFormat.wBitsPerSample * mFormat.nChannels / 8; + mFormat.nBlockAlign = static_cast(mFormat.wBitsPerSample * mFormat.nChannels / 8); mFormat.nSamplesPerSec = mDevice->Frequency; mFormat.nAvgBytesPerSec = mFormat.nSamplesPerSec * mFormat.nBlockAlign; mFormat.cbSize = 0; @@ -500,9 +500,9 @@ ALCenum WinMMCapture::open(const ALCchar *name) mFormat = WAVEFORMATEX{}; mFormat.wFormatTag = (mDevice->FmtType == DevFmtFloat) ? WAVE_FORMAT_IEEE_FLOAT : WAVE_FORMAT_PCM; - mFormat.nChannels = mDevice->channelsFromFmt(); - mFormat.wBitsPerSample = mDevice->bytesFromFmt() * 8; - mFormat.nBlockAlign = mFormat.wBitsPerSample * mFormat.nChannels / 8; + mFormat.nChannels = static_cast(mDevice->channelsFromFmt()); + mFormat.wBitsPerSample = static_cast(mDevice->bytesFromFmt() * 8); + mFormat.nBlockAlign = static_cast(mFormat.wBitsPerSample * mFormat.nChannels / 8); mFormat.nSamplesPerSec = mDevice->Frequency; mFormat.nAvgBytesPerSec = mFormat.nSamplesPerSec * mFormat.nBlockAlign; mFormat.cbSize = 0; -- cgit v1.2.3 From 2c348cecb68bd3a71d388547d6b3330f9cebbfad Mon Sep 17 00:00:00 2001 From: Chris Robinson Date: Sat, 14 Sep 2019 16:55:28 -0700 Subject: Fix some more implicit conversions noted by GCC --- al/source.cpp | 6 +++--- alc/alc.cpp | 34 +++++++++++++++++-------------- alc/alu.cpp | 10 ++++----- alc/backends/alsa.cpp | 2 +- alc/backends/coreaudio.cpp | 17 ++++++++-------- alc/backends/opensl.cpp | 6 +++--- alc/backends/pulseaudio.cpp | 2 +- alc/bs2b.cpp | 4 ++-- alc/converter.cpp | 2 +- alc/effects/autowah.cpp | 9 +++++---- alc/effects/chorus.cpp | 32 +++++++++++++++-------------- alc/effects/echo.cpp | 6 ++++-- alc/effects/fshifter.cpp | 3 ++- alc/effects/modulator.cpp | 2 +- alc/effects/pshifter.cpp | 19 +++++++++--------- alc/effects/vmorpher.cpp | 14 +++++++------ alc/hrtf.cpp | 49 ++++++++++++++++++++++++--------------------- alc/mastering.cpp | 3 +-- alc/mastering.h | 3 +-- alc/mixer/mixer_c.cpp | 9 +++++---- alc/mixer/mixer_neon.cpp | 13 ++++++------ alc/mixer/mixer_sse.cpp | 7 ++++--- alc/mixer/mixer_sse2.cpp | 2 +- alc/mixer/mixer_sse41.cpp | 2 +- alc/mixvoice.cpp | 18 +++++++++-------- common/almalloc.cpp | 6 +++--- examples/alrecord.c | 5 +++-- examples/altonegen.c | 2 +- examples/common/alhelpers.c | 4 ++-- 29 files changed, 156 insertions(+), 135 deletions(-) (limited to 'alc/backends/alsa.cpp') diff --git a/al/source.cpp b/al/source.cpp index 478ee3d2..733758f7 100644 --- a/al/source.cpp +++ b/al/source.cpp @@ -310,8 +310,8 @@ ALdouble GetSourceOffset(ALsource *Source, ALenum name, ALCcontext *context) const ALbufferlistitem *BufferList{Source->queue}; const ALbuffer *BufferFmt{nullptr}; - ALboolean readFin{AL_FALSE}; ALuint totalBufferLen{0u}; + bool readFin{false}; while(BufferList) { @@ -1662,7 +1662,7 @@ bool GetSourcedv(ALsource *Source, ALCcontext *Context, SourceProp prop, const a case AL_SEC_OFFSET_CLOCK_SOFT: CHECKSIZE(values, 2); values[0] = GetSourceSecOffset(Source, Context, &srcclock); - values[1] = srcclock.count() / 1000000000.0; + values[1] = static_cast(srcclock.count()) / 1000000000.0; return true; case AL_POSITION: @@ -2851,7 +2851,7 @@ START_API_FUNC if(device->AvgSpeakerDist > 0.0f) { const ALfloat w1{SPEEDOFSOUNDMETRESPERSEC / - (device->AvgSpeakerDist * device->Frequency)}; + (device->AvgSpeakerDist * static_cast(device->Frequency))}; auto init_nfc = [w1](ALvoice::ChannelData &chandata) -> void { chandata.mDryParams.NFCtrlFilter.init(w1); }; std::for_each(voice->mChans.begin(), voice->mChans.begin()+voice->mNumChannels, diff --git a/alc/alc.cpp b/alc/alc.cpp index 408b3ca3..8e9d3963 100644 --- a/alc/alc.cpp +++ b/alc/alc.cpp @@ -1587,9 +1587,9 @@ static void alcSetError(ALCdevice *device, ALCenum errorCode) static std::unique_ptr CreateDeviceLimiter(const ALCdevice *device, const ALfloat threshold) { - return CompressorInit(static_cast(device->RealOut.Buffer.size()), device->Frequency, - AL_TRUE, AL_TRUE, AL_TRUE, AL_TRUE, AL_TRUE, 0.001f, 0.002f, 0.0f, 0.0f, threshold, - INFINITY, 0.0f, 0.020f, 0.200f); + return CompressorInit(static_cast(device->RealOut.Buffer.size()), + static_cast(device->Frequency), AL_TRUE, AL_TRUE, AL_TRUE, AL_TRUE, AL_TRUE, 0.001f, + 0.002f, 0.0f, 0.0f, threshold, INFINITY, 0.0f, 0.020f, 0.200f); } /* UpdateClockBase @@ -2145,17 +2145,21 @@ static ALCenum UpdateDeviceParams(ALCdevice *device, const ALCint *attrList) if(old_sends != device->NumAuxSends) { - if(source->Send.size() > static_cast(device->NumAuxSends)) - std::for_each(source->Send.begin()+device->NumAuxSends, source->Send.end(), - [](ALsource::SendData &send) -> void - { - if(send.Slot) - DecrementRef(send.Slot->ref); - send.Slot = nullptr; - }); - - source->Send.resize(static_cast(device->NumAuxSends), - ALsource::SendData{nullptr, 1.0f, 1.0f, LOWPASSFREQREF, 1.0f, HIGHPASSFREQREF}); + if(source->Send.size() > device->NumAuxSends) + { + auto clear_send = [](ALsource::SendData &send) -> void + { + if(send.Slot) + DecrementRef(send.Slot->ref); + send.Slot = nullptr; + }; + auto send_begin = source->Send.begin() + + static_cast(device->NumAuxSends); + std::for_each(send_begin, source->Send.end(), clear_send); + } + + source->Send.resize(device->NumAuxSends, + {nullptr, 1.0f, 1.0f, LOWPASSFREQREF, 1.0f, HIGHPASSFREQREF}); source->Send.shrink_to_fit(); } @@ -2209,7 +2213,7 @@ static ALCenum UpdateDeviceParams(ALCdevice *device, const ALCint *attrList) { /* Reinitialize the NFC filters for new parameters. */ const ALfloat w1{SPEEDOFSOUNDMETRESPERSEC / - (device->AvgSpeakerDist * device->Frequency)}; + (device->AvgSpeakerDist * static_cast(device->Frequency))}; auto init_nfc = [w1](ALvoice::ChannelData &chandata) -> void { chandata.mDryParams.NFCtrlFilter.init(w1); }; std::for_each(voice.mChans.begin(), voice.mChans.begin()+voice.mNumChannels, diff --git a/alc/alu.cpp b/alc/alu.cpp index 0def577e..d7acf8d3 100644 --- a/alc/alu.cpp +++ b/alc/alu.cpp @@ -201,19 +201,19 @@ void ALCdevice::ProcessBs2b(const size_t SamplesToDo) */ void BsincPrepare(const ALuint increment, BsincState *state, const BSincTable *table) { - ALsizei si{BSINC_SCALE_COUNT - 1}; - ALfloat sf{0.0f}; + size_t si{BSINC_SCALE_COUNT - 1}; + float sf{0.0f}; if(increment > FRACTIONONE) { - sf = static_castFRACTIONONE / increment; + sf = FRACTIONONE / static_cast(increment); sf = maxf(0.0f, (BSINC_SCALE_COUNT-1) * (sf-table->scaleBase) * table->scaleRange); - si = float2int(sf); + si = float2uint(sf); /* The interpolation factor is fit to this diagonally-symmetric curve * to reduce the transition ripple caused by interpolating different * scales of the sinc function. */ - sf = 1.0f - std::cos(std::asin(sf - si)); + sf = 1.0f - std::cos(std::asin(sf - static_cast(si))); } state->sf = sf; diff --git a/alc/backends/alsa.cpp b/alc/backends/alsa.cpp index cd85afaf..b797c768 100644 --- a/alc/backends/alsa.cpp +++ b/alc/backends/alsa.cpp @@ -1112,7 +1112,7 @@ ALCenum AlsaCapture::captureSamples(ALCvoid *buffer, ALCuint samples) } buffer = static_cast(buffer) + amt; - samples -= amt; + samples -= static_cast(amt); } if(samples > 0) std::fill_n(static_cast(buffer), snd_pcm_frames_to_bytes(mPcmHandle, samples), diff --git a/alc/backends/coreaudio.cpp b/alc/backends/coreaudio.cpp index 39f6241a..99b06b7a 100644 --- a/alc/backends/coreaudio.cpp +++ b/alc/backends/coreaudio.cpp @@ -177,7 +177,7 @@ ALCboolean CoreAudioPlayback::reset() { mDevice->BufferSize = static_cast(uint64_t{mDevice->BufferSize} * streamFormat.mSampleRate / mDevice->Frequency); - mDevice->Frequency = streamFormat.mSampleRate; + mDevice->Frequency = static_cast(streamFormat.mSampleRate); } /* FIXME: How to tell what channels are what in the output device, and how @@ -357,7 +357,8 @@ OSStatus CoreAudioCapture::RecordProc(AudioUnitRenderActionFlags*, } audiobuf = { { 0 } }; auto rec_vec = mRing->getWriteVector(); - inNumberFrames = minz(inNumberFrames, rec_vec.first.len+rec_vec.second.len); + inNumberFrames = static_cast(minz(inNumberFrames, + rec_vec.first.len+rec_vec.second.len)); // Fill the ringbuffer's two segments with data from the input device if(rec_vec.first.len >= inNumberFrames) @@ -369,7 +370,7 @@ OSStatus CoreAudioCapture::RecordProc(AudioUnitRenderActionFlags*, } else { - const size_t remaining{inNumberFrames-rec_vec.first.len}; + const auto remaining = static_cast(inNumberFrames - rec_vec.first.len); audiobuf.list.mNumberBuffers = 2; audiobuf.list.mBuffers[0].mNumberChannels = mFormat.mChannelsPerFrame; audiobuf.list.mBuffers[0].mData = rec_vec.first.buf; @@ -594,7 +595,7 @@ ALCenum CoreAudioCapture::open(const ALCchar *name) // Set the AudioUnit output format frame count uint64_t FrameCount64{mDevice->UpdateSize}; - FrameCount64 = (FrameCount64*outputFormat.mSampleRate + mDevice->Frequency-1) / + FrameCount64 = static_cast(FrameCount64*outputFormat.mSampleRate + mDevice->Frequency-1) / mDevice->Frequency; FrameCount64 += MAX_RESAMPLE_PADDING*2; if(FrameCount64 > std::numeric_limits::max()/2) @@ -615,8 +616,8 @@ ALCenum CoreAudioCapture::open(const ALCchar *name) // Set up sample converter if needed if(outputFormat.mSampleRate != mDevice->Frequency) mConverter = CreateSampleConverter(mDevice->FmtType, mDevice->FmtType, - mFormat.mChannelsPerFrame, hardwareFormat.mSampleRate, mDevice->Frequency, - BSinc24Resampler); + mFormat.mChannelsPerFrame, static_cast(hardwareFormat.mSampleRate), + mDevice->Frequency, BSinc24Resampler); mRing = CreateRingBuffer(outputFrameCount, mFrameSize, false); if(!mRing) return ALC_INVALID_VALUE; @@ -671,8 +672,8 @@ ALCenum CoreAudioCapture::captureSamples(void *buffer, ALCuint samples) ALCuint CoreAudioCapture::availableSamples() { - if(!mConverter) return mRing->readSpace(); - return mConverter->availableOut(mRing->readSpace()); + if(!mConverter) return static_cast(mRing->readSpace()); + return mConverter->availableOut(static_cast(mRing->readSpace())); } } // namespace diff --git a/alc/backends/opensl.cpp b/alc/backends/opensl.cpp index 3ec2177f..06d5cd40 100644 --- a/alc/backends/opensl.cpp +++ b/alc/backends/opensl.cpp @@ -170,7 +170,7 @@ struct OpenSLPlayback final : public BackendBase { RingBufferPtr mRing{nullptr}; al::semaphore mSem; - ALsizei mFrameSize{0}; + ALuint mFrameSize{0}; std::atomic mKillNow{true}; std::thread mThread; @@ -630,7 +630,7 @@ struct OpenSLCapture final : public BackendBase { RingBufferPtr mRing{nullptr}; ALCuint mSplOffset{0u}; - ALsizei mFrameSize{0}; + ALuint mFrameSize{0}; DEF_NEWDEL(OpenSLCapture) }; @@ -851,7 +851,7 @@ void OpenSLCapture::stop() ALCenum OpenSLCapture::captureSamples(void *buffer, ALCuint samples) { - ALsizei chunk_size = mDevice->UpdateSize * mFrameSize; + ALuint chunk_size{mDevice->UpdateSize * mFrameSize}; SLAndroidSimpleBufferQueueItf bufferQueue; SLresult result; ALCuint i; diff --git a/alc/backends/pulseaudio.cpp b/alc/backends/pulseaudio.cpp index 08420748..30c13a69 100644 --- a/alc/backends/pulseaudio.cpp +++ b/alc/backends/pulseaudio.cpp @@ -1324,7 +1324,7 @@ ALCenum PulseCapture::captureSamples(ALCvoid *buffer, ALCuint samples) /* Capture is done in fragment-sized chunks, so we loop until we get all * that's available */ - mLastReadable -= dstbuf.size(); + mLastReadable -= static_cast(dstbuf.size()); std::lock_guard _{pulse_lock}; while(!dstbuf.empty()) { diff --git a/alc/bs2b.cpp b/alc/bs2b.cpp index fb75188c..00207bc0 100644 --- a/alc/bs2b.cpp +++ b/alc/bs2b.cpp @@ -91,11 +91,11 @@ static void init(struct bs2b *bs2b) * $d = 1 / 2 / pi / $fc; * $x = exp(-1 / $d); */ - x = std::exp(-al::MathDefs::Tau() * Fc_lo / bs2b->srate); + x = std::exp(-al::MathDefs::Tau() * Fc_lo / static_cast(bs2b->srate)); bs2b->b1_lo = x; bs2b->a0_lo = G_lo * (1.0f - x) * g; - x = std::exp(-al::MathDefs::Tau() * Fc_hi / bs2b->srate); + x = std::exp(-al::MathDefs::Tau() * Fc_hi / static_cast(bs2b->srate)); bs2b->b1_hi = x; bs2b->a0_hi = (1.0f - G_hi * (1.0f - x)) * g; bs2b->a1_hi = -x * g; diff --git a/alc/converter.cpp b/alc/converter.cpp index 2913f533..2ad2ac3b 100644 --- a/alc/converter.cpp +++ b/alc/converter.cpp @@ -27,7 +27,7 @@ template<> inline ALfloat LoadSample(DevFmtTypeTraits::T template<> inline ALfloat LoadSample(DevFmtTypeTraits::Type val) noexcept { return val * (1.0f/32768.0f); } template<> inline ALfloat LoadSample(DevFmtTypeTraits::Type val) noexcept -{ return val * (1.0f/2147483648.0f); } +{ return static_cast(val) * (1.0f/2147483648.0f); } template<> inline ALfloat LoadSample(DevFmtTypeTraits::Type val) noexcept { return val; } diff --git a/alc/effects/autowah.cpp b/alc/effects/autowah.cpp index f28cfd54..5e396d0c 100644 --- a/alc/effects/autowah.cpp +++ b/alc/effects/autowah.cpp @@ -107,16 +107,17 @@ ALboolean ALautowahState::deviceUpdate(const ALCdevice*) void ALautowahState::update(const ALCcontext *context, const ALeffectslot *slot, const EffectProps *props, const EffectTarget target) { const ALCdevice *device{context->mDevice.get()}; + const auto frequency = static_cast(device->Frequency); const ALfloat ReleaseTime{clampf(props->Autowah.ReleaseTime, 0.001f, 1.0f)}; - mAttackRate = expf(-1.0f / (props->Autowah.AttackTime*device->Frequency)); - mReleaseRate = expf(-1.0f / (ReleaseTime*device->Frequency)); + mAttackRate = std::exp(-1.0f / (props->Autowah.AttackTime*frequency)); + mReleaseRate = std::exp(-1.0f / (ReleaseTime*frequency)); /* 0-20dB Resonance Peak gain */ mResonanceGain = std::sqrt(std::log10(props->Autowah.Resonance)*10.0f / 3.0f); mPeakGain = 1.0f - std::log10(props->Autowah.PeakGain/AL_AUTOWAH_MAX_PEAK_GAIN); - mFreqMinNorm = MIN_FREQ / device->Frequency; - mBandwidthNorm = (MAX_FREQ-MIN_FREQ) / device->Frequency; + mFreqMinNorm = MIN_FREQ / frequency; + mBandwidthNorm = (MAX_FREQ-MIN_FREQ) / frequency; mOutTarget = target.Main->Buffer; for(size_t i{0u};i < slot->Wet.Buffer.size();++i) diff --git a/alc/effects/chorus.cpp b/alc/effects/chorus.cpp index 6e73f1f0..0e3c9d89 100644 --- a/alc/effects/chorus.cpp +++ b/alc/effects/chorus.cpp @@ -64,8 +64,8 @@ void GetTriangleDelays(ALuint *delays, const ALuint start_offset, const ALuint l auto gen_lfo = [&offset,lfo_range,lfo_scale,depth,delay]() -> ALuint { offset = (offset+1)%lfo_range; - return static_cast( - fastf2i((1.0f - std::abs(2.0f - lfo_scale*offset)) * depth) + delay); + const float offset_norm{static_cast(offset) * lfo_scale}; + return static_cast(fastf2i((1.0f-std::abs(2.0f-offset_norm)) * depth) + delay); }; std::generate_n(delays, todo, gen_lfo); } @@ -80,7 +80,8 @@ void GetSinusoidDelays(ALuint *delays, const ALuint start_offset, const ALuint l auto gen_lfo = [&offset,lfo_range,lfo_scale,depth,delay]() -> ALuint { offset = (offset+1)%lfo_range; - return static_cast(fastf2i(std::sin(lfo_scale*offset) * depth) + delay); + const float offset_norm{static_cast(offset) * lfo_scale}; + return static_cast(fastf2i(std::sin(offset_norm)*depth) + delay); }; std::generate_n(delays, todo, gen_lfo); } @@ -118,7 +119,8 @@ ALboolean ChorusState::deviceUpdate(const ALCdevice *Device) { constexpr ALfloat max_delay{maxf(AL_CHORUS_MAX_DELAY, AL_FLANGER_MAX_DELAY)}; - const size_t maxlen{NextPowerOf2(float2uint(max_delay*2.0f*Device->Frequency) + 1u)}; + const auto frequency = static_cast(Device->Frequency); + const size_t maxlen{NextPowerOf2(float2uint(max_delay*2.0f*frequency) + 1u)}; if(maxlen != mSampleBuffer.size()) { mSampleBuffer.resize(maxlen); @@ -153,9 +155,11 @@ void ChorusState::update(const ALCcontext *Context, const ALeffectslot *Slot, co * delay and depth to allow enough padding for resampling. */ const ALCdevice *device{Context->mDevice.get()}; - const auto frequency = static_cast(device->Frequency); + const auto frequency = static_cast(device->Frequency); + mDelay = maxi(float2int(props->Chorus.Delay*frequency*FRACTIONONE + 0.5f), mindelay); - mDepth = minf(props->Chorus.Depth * mDelay, static_cast(mDelay - mindelay)); + mDepth = minf(props->Chorus.Depth * static_cast(mDelay), + static_cast(mDelay - mindelay)); mFeedback = props->Chorus.Feedback; @@ -188,10 +192,10 @@ void ChorusState::update(const ALCcontext *Context, const ALeffectslot *Slot, co switch(mWaveform) { case WaveForm::Triangle: - mLfoScale = 4.0f / mLfoRange; + mLfoScale = 4.0f / static_cast(mLfoRange); break; case WaveForm::Sinusoid: - mLfoScale = al::MathDefs::Tau() / mLfoRange; + mLfoScale = al::MathDefs::Tau() / static_cast(mLfoRange); break; } @@ -229,7 +233,7 @@ void ChorusState::process(const size_t samplesToDo, const al::span(todo)) % mLfoRange; alignas(16) ALfloat temps[2][256]; for(size_t i{0u};i < todo;i++) @@ -239,17 +243,15 @@ void ChorusState::process(const size_t samplesToDo, const al::span>FRACTIONBITS)}; - ALfloat mu{(moddelays[0][i]&FRACTIONMASK) * (1.0f/FRACTIONONE)}; + ALfloat mu{static_cast(moddelays[0][i]&FRACTIONMASK) * (1.0f/FRACTIONONE)}; temps[0][i] = cubic(delaybuf[(delay+1) & bufmask], delaybuf[(delay ) & bufmask], - delaybuf[(delay-1) & bufmask], delaybuf[(delay-2) & bufmask], - mu); + delaybuf[(delay-1) & bufmask], delaybuf[(delay-2) & bufmask], mu); // Tap for the right output. delay = offset - (moddelays[1][i]>>FRACTIONBITS); - mu = (moddelays[1][i]&FRACTIONMASK) * (1.0f/FRACTIONONE); + mu = static_cast(moddelays[1][i]&FRACTIONMASK) * (1.0f/FRACTIONONE); temps[1][i] = cubic(delaybuf[(delay+1) & bufmask], delaybuf[(delay ) & bufmask], - delaybuf[(delay-1) & bufmask], delaybuf[(delay-2) & bufmask], - mu); + delaybuf[(delay-1) & bufmask], delaybuf[(delay-2) & bufmask], mu); // Accumulate feedback from the average delay of the taps. delaybuf[offset&bufmask] += delaybuf[(offset-avgdelay) & bufmask] * feedback; diff --git a/alc/effects/echo.cpp b/alc/effects/echo.cpp index 47c0fedb..a9213df5 100644 --- a/alc/effects/echo.cpp +++ b/alc/effects/echo.cpp @@ -66,10 +66,12 @@ struct EchoState final : public EffectState { ALboolean EchoState::deviceUpdate(const ALCdevice *Device) { + const auto frequency = static_cast(Device->Frequency); + // Use the next power of 2 for the buffer length, so the tap offsets can be // wrapped using a mask instead of a modulo - const ALuint maxlen{NextPowerOf2(float2uint(AL_ECHO_MAX_DELAY*Device->Frequency + 0.5f) + - float2uint(AL_ECHO_MAX_LRDELAY*Device->Frequency + 0.5f))}; + const ALuint maxlen{NextPowerOf2(float2uint(AL_ECHO_MAX_DELAY*frequency + 0.5f) + + float2uint(AL_ECHO_MAX_LRDELAY*frequency + 0.5f))}; if(maxlen != mSampleBuffer.size()) { mSampleBuffer.resize(maxlen); diff --git a/alc/effects/fshifter.cpp b/alc/effects/fshifter.cpp index c015831c..1b935047 100644 --- a/alc/effects/fshifter.cpp +++ b/alc/effects/fshifter.cpp @@ -51,7 +51,8 @@ std::array InitHannWindow() /* Create lookup table of the Hann window for the desired size, i.e. HIL_SIZE */ for(size_t i{0};i < HIL_SIZE>>1;i++) { - const double val{std::sin(al::MathDefs::Pi() * i / double{HIL_SIZE-1})}; + constexpr double scale{al::MathDefs::Pi() / double{HIL_SIZE-1}}; + const double val{std::sin(static_cast(i) * scale)}; ret[i] = ret[HIL_SIZE-1-i] = val * val; } return ret; diff --git a/alc/effects/modulator.cpp b/alc/effects/modulator.cpp index fbc6377c..8042378a 100644 --- a/alc/effects/modulator.cpp +++ b/alc/effects/modulator.cpp @@ -146,7 +146,7 @@ void ModulatorState::process(const size_t samplesToDo, const al::span(mStep * td); mIndex &= WAVEFORM_FRACMASK; auto chandata = std::addressof(mChans[0]); diff --git a/alc/effects/pshifter.cpp b/alc/effects/pshifter.cpp index a4d66706..d7ba072e 100644 --- a/alc/effects/pshifter.cpp +++ b/alc/effects/pshifter.cpp @@ -57,7 +57,8 @@ std::array InitHannWindow() /* Create lookup table of the Hann window for the desired size, i.e. HIL_SIZE */ for(size_t i{0};i < STFT_SIZE>>1;i++) { - const double val{std::sin(al::MathDefs::Pi() * i / ALdouble{STFT_SIZE-1})}; + constexpr double scale{al::MathDefs::Pi() / double{STFT_SIZE-1}}; + const double val{std::sin(static_cast(i) * scale)}; ret[i] = ret[STFT_SIZE-1-i] = val * val; } return ret; @@ -129,7 +130,7 @@ ALboolean PshifterState::deviceUpdate(const ALCdevice *device) mCount = FIFO_LATENCY; mPitchShiftI = FRACTIONONE; mPitchShift = 1.0f; - mFreqPerBin = device->Frequency / static_cast(STFT_SIZE); + mFreqPerBin = static_cast(device->Frequency) / float{STFT_SIZE}; std::fill(std::begin(mInFIFO), std::end(mInFIFO), 0.0f); std::fill(std::begin(mOutFIFO), std::end(mOutFIFO), 0.0f); @@ -152,7 +153,7 @@ void PshifterState::update(const ALCcontext*, const ALeffectslot *slot, const Ef static_cast(props->Pshifter.CoarseTune*100 + props->Pshifter.FineTune) / 1200.0f )}; mPitchShiftI = fastf2u(pitch*FRACTIONONE); - mPitchShift = mPitchShiftI * (1.0f/FRACTIONONE); + mPitchShift = static_cast(mPitchShiftI) * (1.0f/FRACTIONONE); ALfloat coeffs[MAX_AMBI_CHANNELS]; CalcDirectionCoeffs({0.0f, 0.0f, -1.0f}, 0.0f, coeffs); @@ -187,7 +188,7 @@ void PshifterState::process(const size_t samplesToDo, const al::spanVmorpher.Waveform == AL_VOCAL_MORPHER_WAVEFORM_TRIANGLE)*/ mGetSamples = Oscillate; - const ALfloat pitchA{std::pow(2.0f, props->Vmorpher.PhonemeACoarseTuning / 12.0f)}; - const ALfloat pitchB{std::pow(2.0f, props->Vmorpher.PhonemeBCoarseTuning / 12.0f)}; + const ALfloat pitchA{std::pow(2.0f, + static_cast(props->Vmorpher.PhonemeACoarseTuning) / 12.0f)}; + const ALfloat pitchB{std::pow(2.0f, + static_cast(props->Vmorpher.PhonemeBCoarseTuning) / 12.0f)}; auto vowelA = getFiltersByPhoneme(props->Vmorpher.PhonemeA, frequency, pitchA); auto vowelB = getFiltersByPhoneme(props->Vmorpher.PhonemeB, frequency, pitchB); @@ -255,7 +257,7 @@ void VmorpherState::process(const size_t samplesToDo, const al::span(mStep * td); mIndex &= WAVEFORM_FRACMASK; auto chandata = std::addressof(mChans[0]); diff --git a/alc/hrtf.cpp b/alc/hrtf.cpp index bd6ecb3a..e20bf0a9 100644 --- a/alc/hrtf.cpp +++ b/alc/hrtf.cpp @@ -182,10 +182,11 @@ struct IdxBlend { ALsizei idx; ALfloat blend; }; */ IdxBlend CalcEvIndex(ALsizei evcount, ALfloat ev) { - ev = (al::MathDefs::Pi()*0.5f + ev) * (evcount-1) / al::MathDefs::Pi(); + ev = (al::MathDefs::Pi()*0.5f + ev) * static_cast(evcount-1) / + al::MathDefs::Pi(); ALsizei idx{float2int(ev)}; - return IdxBlend{mini(idx, evcount-1), ev-idx}; + return IdxBlend{mini(idx, evcount-1), ev-static_cast(idx)}; } /* Calculate the azimuth index given the polar azimuth in radians. This will @@ -193,10 +194,11 @@ IdxBlend CalcEvIndex(ALsizei evcount, ALfloat ev) */ IdxBlend CalcAzIndex(ALsizei azcount, ALfloat az) { - az = (al::MathDefs::Tau()+az) * azcount / al::MathDefs::Tau(); + az = (al::MathDefs::Tau()+az) * static_cast(azcount) / + al::MathDefs::Tau(); ALsizei idx{float2int(az)}; - return IdxBlend{idx%azcount, az-idx}; + return IdxBlend{idx%azcount, az-static_cast(idx)}; } } // namespace @@ -303,24 +305,25 @@ void BuildBFormatHrtf(const HrtfEntry *Hrtf, DirectHrtfState *state, const ALuin ASSUME(NumChannels > 0); ASSUME(AmbiCount > 0); - auto &field = Hrtf->field[0]; ALuint min_delay{HRTF_HISTORY_LENGTH}; ALuint max_delay{0}; auto idx = al::vector(AmbiCount); - auto calc_idxs = [Hrtf,&field,&max_delay,&min_delay](const AngularPoint &pt) noexcept -> ALuint + auto calc_idxs = [Hrtf,&max_delay,&min_delay](const AngularPoint &pt) noexcept -> ALuint { + auto &field = Hrtf->field[0]; /* Calculate elevation index. */ - const auto evidx = clampi(float2int((90.0f+pt.Elev)*(field.evCount-1)/180.0f + 0.5f), - 0, field.evCount-1); + const auto ev_limit = static_cast(field.evCount-1); + const ALuint evidx{float2uint(clampf((90.0f+pt.Elev)/180.0f, 0.0f, 1.0f)*ev_limit + 0.5f)}; const ALuint azcount{Hrtf->elev[evidx].azCount}; const ALuint iroffset{Hrtf->elev[evidx].irOffset}; /* Calculate azimuth index for this elevation. */ - const auto azidx = static_cast((360.0f+pt.Azim)*azcount/360.0f + 0.5f) % azcount; + const float az_norm{(360.0f*pt.Azim) / 360.0f}; + const ALuint azidx{float2uint(az_norm*static_cast(azcount) + 0.5f) % azcount}; /* Calculate the index for the impulse response. */ - ALuint idx{iroffset + azidx}; + const ALuint idx{iroffset + azidx}; min_delay = minu(min_delay, minu(Hrtf->delays[idx][0], Hrtf->delays[idx][1])); max_delay = maxu(max_delay, maxu(Hrtf->delays[idx][0], Hrtf->delays[idx][1])); @@ -594,7 +597,7 @@ std::unique_ptr LoadHrtf00(std::istream &data, const char *filename) if(failed) return nullptr; - al::vector evOffset(evCount); + auto evOffset = al::vector(evCount); for(auto &val : evOffset) val = GetLE_ALushort(data); if(!data || data.eof()) @@ -619,10 +622,10 @@ std::unique_ptr LoadHrtf00(std::istream &data, const char *filename) if(failed) return nullptr; - al::vector azCount(evCount); + auto azCount = al::vector(evCount); for(size_t i{1};i < evCount;i++) { - azCount[i-1] = evOffset[i] - evOffset[i-1]; + azCount[i-1] = static_cast(evOffset[i] - evOffset[i-1]); if(azCount[i-1] < MIN_AZ_COUNT || azCount[i-1] > MAX_AZ_COUNT) { ERR("Unsupported azimuth count: azCount[%zd]=%d (%d to %d)\n", @@ -630,7 +633,7 @@ std::unique_ptr LoadHrtf00(std::istream &data, const char *filename) failed = AL_TRUE; } } - azCount.back() = irCount - evOffset.back(); + azCount.back() = static_cast(irCount - evOffset.back()); if(azCount.back() < MIN_AZ_COUNT || azCount.back() > MAX_AZ_COUNT) { ERR("Unsupported azimuth count: azCount[%zu]=%d (%d to %d)\n", @@ -640,8 +643,8 @@ std::unique_ptr LoadHrtf00(std::istream &data, const char *filename) if(failed) return nullptr; - al::vector> coeffs(irSize*irCount); - al::vector> delays(irCount); + auto coeffs = al::vector>(irSize*irCount); + auto delays = al::vector>(irCount); for(auto &val : coeffs) val[0] = GetLE_ALshort(data) / 32768.0f; for(auto &val : delays) @@ -711,7 +714,7 @@ std::unique_ptr LoadHrtf01(std::istream &data, const char *filename) if(failed) return nullptr; - al::vector azCount(evCount); + auto azCount = al::vector(evCount); std::generate(azCount.begin(), azCount.end(), std::bind(GetLE_ALubyte, std::ref(data))); if(!data || data.eof()) { @@ -735,12 +738,12 @@ std::unique_ptr LoadHrtf01(std::istream &data, const char *filename) ALushort irCount{azCount[0]}; for(size_t i{1};i < evCount;i++) { - evOffset[i] = evOffset[i-1] + azCount[i-1]; + evOffset[i] = static_cast(evOffset[i-1] + azCount[i-1]); irCount += azCount[i]; } - al::vector> coeffs(irSize*irCount); - al::vector> delays(irCount); + auto coeffs = al::vector>(irSize*irCount); + auto delays = al::vector>(irCount); for(auto &val : coeffs) val[0] = GetLE_ALshort(data) / 32768.0f; for(auto &val : delays) @@ -903,7 +906,7 @@ std::unique_ptr LoadHrtf02(std::istream &data, const char *filename) else if(sampleType == SAMPLETYPE_S24) { for(auto &val : coeffs) - val[0] = GetLE_ALint24(data) / 8388608.0f; + val[0] = static_cast(GetLE_ALint24(data)) / 8388608.0f; } for(auto &val : delays) val[0] = GetLE_ALubyte(data); @@ -935,8 +938,8 @@ std::unique_ptr LoadHrtf02(std::istream &data, const char *filename) { for(auto &val : coeffs) { - val[0] = GetLE_ALint24(data) / 8388608.0f; - val[1] = GetLE_ALint24(data) / 8388608.0f; + val[0] = static_cast(GetLE_ALint24(data)) / 8388608.0f; + val[1] = static_cast(GetLE_ALint24(data)) / 8388608.0f; } } for(auto &val : delays) diff --git a/alc/mastering.cpp b/alc/mastering.cpp index 2f575f35..d0a2f78a 100644 --- a/alc/mastering.cpp +++ b/alc/mastering.cpp @@ -337,7 +337,7 @@ void SignalDelay(Compressor *Comp, const ALuint SamplesToDo, FloatBufferLine *Ou * ReleaseTimeMin - Release time (in seconds). Acts as a maximum when * automating release time. */ -std::unique_ptr CompressorInit(const ALuint NumChans, const ALuint SampleRate, +std::unique_ptr CompressorInit(const ALuint NumChans, const ALfloat SampleRate, const ALboolean AutoKnee, const ALboolean AutoAttack, const ALboolean AutoRelease, const ALboolean AutoPostGain, const ALboolean AutoDeclip, const ALfloat LookAheadTime, const ALfloat HoldTime, const ALfloat PreGainDb, const ALfloat PostGainDb, @@ -363,7 +363,6 @@ std::unique_ptr CompressorInit(const ALuint NumChans, const ALuint S auto Comp = std::unique_ptr{new (al_calloc(16, size)) Compressor{}}; Comp->mNumChans = NumChans; - Comp->mSampleRate = SampleRate; Comp->mAuto.Knee = AutoKnee != AL_FALSE; Comp->mAuto.Attack = AutoAttack != AL_FALSE; Comp->mAuto.Release = AutoRelease != AL_FALSE; diff --git a/alc/mastering.h b/alc/mastering.h index 6c8fc628..851381e9 100644 --- a/alc/mastering.h +++ b/alc/mastering.h @@ -24,7 +24,6 @@ struct SlidingHold; */ struct Compressor { ALuint mNumChans{0u}; - ALuint mSampleRate{0u}; struct { bool Knee : 1; @@ -94,7 +93,7 @@ struct Compressor { * ReleaseTimeMin - Release time (in seconds). Acts as a maximum when * automating release time. */ -std::unique_ptr CompressorInit(const ALuint NumChans, const ALuint SampleRate, +std::unique_ptr CompressorInit(const ALuint NumChans, const ALfloat SampleRate, const ALboolean AutoKnee, const ALboolean AutoAttack, const ALboolean AutoRelease, const ALboolean AutoPostGain, const ALboolean AutoDeclip, const ALfloat LookAheadTime, const ALfloat HoldTime, const ALfloat PreGainDb, const ALfloat PostGainDb, diff --git a/alc/mixer/mixer_c.cpp b/alc/mixer/mixer_c.cpp index 720b264b..74315dd5 100644 --- a/alc/mixer/mixer_c.cpp +++ b/alc/mixer/mixer_c.cpp @@ -16,9 +16,9 @@ namespace { inline ALfloat do_point(const InterpState&, const ALfloat *RESTRICT vals, const ALuint) { return vals[0]; } inline ALfloat do_lerp(const InterpState&, const ALfloat *RESTRICT vals, const ALuint frac) -{ return lerp(vals[0], vals[1], frac * (1.0f/FRACTIONONE)); } +{ return lerp(vals[0], vals[1], static_cast(frac)*(1.0f/FRACTIONONE)); } inline ALfloat do_cubic(const InterpState&, const ALfloat *RESTRICT vals, const ALuint frac) -{ return cubic(vals[0], vals[1], vals[2], vals[3], frac * (1.0f/FRACTIONONE)); } +{ return cubic(vals[0], vals[1], vals[2], vals[3], static_cast(frac)*(1.0f/FRACTIONONE)); } inline ALfloat do_bsinc(const InterpState &istate, const ALfloat *RESTRICT vals, const ALuint frac) { ASSUME(istate.bsinc.m > 0); @@ -26,10 +26,11 @@ inline ALfloat do_bsinc(const InterpState &istate, const ALfloat *RESTRICT vals, // Calculate the phase index and factor. #define FRAC_PHASE_BITDIFF (FRACTIONBITS-BSINC_PHASE_BITS) const ALuint pi{frac >> FRAC_PHASE_BITDIFF}; - const ALfloat pf{(frac & ((1<(frac & ((1<(istate.bsinc.m)*pi*4}; const ALfloat *scd{fil + istate.bsinc.m}; const ALfloat *phd{scd + istate.bsinc.m}; const ALfloat *spd{phd + istate.bsinc.m}; diff --git a/alc/mixer/mixer_neon.cpp b/alc/mixer/mixer_neon.cpp index 852bef38..2f11273a 100644 --- a/alc/mixer/mixer_neon.cpp +++ b/alc/mixer/mixer_neon.cpp @@ -55,10 +55,10 @@ const ALfloat *Resample_(const InterpState*, const ALfloat *RES if(dst_iter != dst.end()) { src += static_cast(vgetq_lane_s32(pos4, 0)); - frac = vgetq_lane_s32(frac4, 0); + frac = static_cast(vgetq_lane_s32(frac4, 0)); do { - *(dst_iter++) = lerp(src[0], src[1], frac * (1.0f/FRACTIONONE)); + *(dst_iter++) = lerp(src[0], src[1], static_cast(frac) * (1.0f/FRACTIONONE)); frac += increment; src += frac>>FRACTIONBITS; @@ -84,14 +84,15 @@ const ALfloat *Resample_(const InterpState *state, const ALflo // Calculate the phase index and factor. #define FRAC_PHASE_BITDIFF (FRACTIONBITS-BSINC_PHASE_BITS) const ALuint pi{frac >> FRAC_PHASE_BITDIFF}; - const ALfloat pf{(frac & ((1<(frac & ((1<(pi*4)}; const float *scd{fil + m}; const float *phd{scd + m}; const float *spd{phd + m}; @@ -179,8 +180,8 @@ void Mix_(const al::span InSamples, const al::span 0) ? 1.0f / static_cast(Counter) : 0.0f}; const bool reached_target{InSamples.size() >= Counter}; const auto min_end = reached_target ? InSamples.begin() + Counter : InSamples.end(); - const auto aligned_end = minz(InSamples.size(), (min_end-InSamples.begin()+3) & ~3u) + - InSamples.begin(); + const auto aligned_end = minz(static_cast(min_end-InSamples.begin()+3) & ~3u, + InSamples.size()) + InSamples.begin(); for(FloatBufferLine &output : OutBuffer) { ALfloat *RESTRICT dst{al::assume_aligned<16>(output.data()+OutPos)}; diff --git a/alc/mixer/mixer_sse.cpp b/alc/mixer/mixer_sse.cpp index 368b8dfe..65eb0dee 100644 --- a/alc/mixer/mixer_sse.cpp +++ b/alc/mixer/mixer_sse.cpp @@ -29,7 +29,8 @@ const ALfloat *Resample_(const InterpState *state, const ALfloa // Calculate the phase index and factor. #define FRAC_PHASE_BITDIFF (FRACTIONBITS-BSINC_PHASE_BITS) const ALuint pi{frac >> FRAC_PHASE_BITDIFF}; - const ALfloat pf{(frac & ((1<(frac & ((1<(const al::span InSamples, const al::span 0) ? 1.0f / static_cast(Counter) : 0.0f}; const bool reached_target{InSamples.size() >= Counter}; const auto min_end = reached_target ? InSamples.begin() + Counter : InSamples.end(); - const auto aligned_end = minz(InSamples.size(), (min_end-InSamples.begin()+3) & ~3u) + - InSamples.begin(); + const auto aligned_end = minz(static_cast(min_end-InSamples.begin()+3) & ~3u, + InSamples.size()) + InSamples.begin(); for(FloatBufferLine &output : OutBuffer) { ALfloat *RESTRICT dst{al::assume_aligned<16>(output.data()+OutPos)}; diff --git a/alc/mixer/mixer_sse2.cpp b/alc/mixer/mixer_sse2.cpp index 38d77fd9..897cd1f7 100644 --- a/alc/mixer/mixer_sse2.cpp +++ b/alc/mixer/mixer_sse2.cpp @@ -72,7 +72,7 @@ const ALfloat *Resample_(const InterpState*, const ALfloat *RES frac = static_cast(_mm_cvtsi128_si32(frac4)); do { - *(dst_iter++) = lerp(src[0], src[1], frac * (1.0f/FRACTIONONE)); + *(dst_iter++) = lerp(src[0], src[1], static_cast(frac) * (1.0f/FRACTIONONE)); frac += increment; src += frac>>FRACTIONBITS; diff --git a/alc/mixer/mixer_sse41.cpp b/alc/mixer/mixer_sse41.cpp index 0a87f76f..cfa21e99 100644 --- a/alc/mixer/mixer_sse41.cpp +++ b/alc/mixer/mixer_sse41.cpp @@ -77,7 +77,7 @@ const ALfloat *Resample_(const InterpState*, const ALfloat *RES frac = static_cast(_mm_cvtsi128_si32(frac4)); do { - *(dst_iter++) = lerp(src[0], src[1], frac * (1.0f/FRACTIONONE)); + *(dst_iter++) = lerp(src[0], src[1], static_cast(frac) * (1.0f/FRACTIONONE)); frac += increment; src += frac>>FRACTIONBITS; diff --git a/alc/mixvoice.cpp b/alc/mixvoice.cpp index 7bdeea5e..d7a32f35 100644 --- a/alc/mixvoice.cpp +++ b/alc/mixvoice.cpp @@ -287,33 +287,35 @@ struct FmtTypeTraits { }; template<> struct FmtTypeTraits { using Type = ALubyte; - static constexpr ALfloat to_float(const Type val) { return (val-128) * (1.0f/128.0f); } + static constexpr ALfloat to_float(const Type val) noexcept + { return val*(1.0f/128.0f) - 128.0f; } }; template<> struct FmtTypeTraits { using Type = ALshort; - static constexpr ALfloat to_float(const Type val) { return val * (1.0f/32768.0f); } + static constexpr ALfloat to_float(const Type val) noexcept { return val*(1.0f/32768.0f); } }; template<> struct FmtTypeTraits { using Type = ALfloat; - static constexpr ALfloat to_float(const Type val) { return val; } + static constexpr ALfloat to_float(const Type val) noexcept { return val; } }; template<> struct FmtTypeTraits { using Type = ALdouble; - static constexpr ALfloat to_float(const Type val) { return static_cast(val); } + static constexpr ALfloat to_float(const Type val) noexcept + { return static_cast(val); } }; template<> struct FmtTypeTraits { using Type = ALubyte; - static constexpr ALfloat to_float(const Type val) + static constexpr ALfloat to_float(const Type val) noexcept { return muLawDecompressionTable[val] * (1.0f/32768.0f); } }; template<> struct FmtTypeTraits { using Type = ALubyte; - static constexpr ALfloat to_float(const Type val) + static constexpr ALfloat to_float(const Type val) noexcept { return aLawDecompressionTable[val] * (1.0f/32768.0f); } }; @@ -363,7 +365,7 @@ const ALfloat *DoFilters(BiquadFilter *lpfilter, BiquadFilter *hpfilter, ALfloat template inline void LoadSampleArray(ALfloat *RESTRICT dst, const al::byte *src, const size_t srcstep, - const size_t samples) + const size_t samples) noexcept { using SampleType = typename FmtTypeTraits::Type; @@ -373,7 +375,7 @@ inline void LoadSampleArray(ALfloat *RESTRICT dst, const al::byte *src, const si } void LoadSamples(ALfloat *RESTRICT dst, const al::byte *src, const size_t srcstep, FmtType srctype, - const size_t samples) + const size_t samples) noexcept { #define HANDLE_FMT(T) case T: LoadSampleArray(dst, src, srcstep, samples); break switch(srctype) diff --git a/common/almalloc.cpp b/common/almalloc.cpp index 8700bddc..842fb400 100644 --- a/common/almalloc.cpp +++ b/common/almalloc.cpp @@ -30,11 +30,11 @@ void *al_malloc(size_t alignment, size_t size) #elif defined(HAVE__ALIGNED_MALLOC) return _aligned_malloc(size, alignment); #else - char *ret = static_cast(malloc(size+alignment)); + auto *ret = static_cast(malloc(size+alignment)); if(ret != nullptr) { *(ret++) = 0x00; - while((reinterpret_cast(ret)&(alignment-1)) != 0) + while((reinterpret_cast(ret)&(alignment-1)) != 0) *(ret++) = 0x55; } return ret; @@ -57,7 +57,7 @@ void al_free(void *ptr) noexcept #else if(ptr != nullptr) { - char *finder = static_cast(ptr); + auto *finder = static_cast(ptr); do { --finder; } while(*finder == 0x55); diff --git a/examples/alrecord.c b/examples/alrecord.c index 627f8540..a66e5471 100644 --- a/examples/alrecord.c +++ b/examples/alrecord.c @@ -54,13 +54,14 @@ static float msvc_strtof(const char *str, char **end) static void fwrite16le(ALushort val, FILE *f) { - ALubyte data[2] = { val&0xff, (val>>8)&0xff }; + ALubyte data[2] = { (ALubyte)(val&0xff), (ALubyte)((val>>8)&0xff) }; fwrite(data, 1, 2, f); } static void fwrite32le(ALuint val, FILE *f) { - ALubyte data[4] = { val&0xff, (val>>8)&0xff, (val>>16)&0xff, (val>>24)&0xff }; + ALubyte data[4] = { (ALubyte)(val&0xff), (ALubyte)((val>>8)&0xff), (ALubyte)((val>>16)&0xff), + (ALubyte)((val>>24)&0xff) }; fwrite(data, 1, 4, f); } diff --git a/examples/altonegen.c b/examples/altonegen.c index aacc3496..26ae788d 100644 --- a/examples/altonegen.c +++ b/examples/altonegen.c @@ -97,7 +97,7 @@ static ALuint CreateWave(enum WaveType type, ALuint freq, ALuint srate) ALenum err; ALuint i; - data_size = srate * sizeof(ALfloat); + data_size = (ALuint)(srate * sizeof(ALfloat)); data = calloc(1, data_size); switch(type) { diff --git a/examples/common/alhelpers.c b/examples/common/alhelpers.c index 730d2e13..0febef43 100644 --- a/examples/common/alhelpers.c +++ b/examples/common/alhelpers.c @@ -175,8 +175,8 @@ int altime_get(void) void al_nssleep(unsigned long nsec) { struct timespec ts, rem; - ts.tv_sec = nsec / 1000000000ul; - ts.tv_nsec = nsec % 1000000000ul; + ts.tv_sec = (time_t)(nsec / 1000000000ul); + ts.tv_nsec = (long)(nsec % 1000000000ul); while(nanosleep(&ts, &rem) == -1 && errno == EINTR) ts = rem; } -- cgit v1.2.3 From c5a3c52822d0ab8e36c2d3d31936eae1da64049f Mon Sep 17 00:00:00 2001 From: Chris Robinson Date: Sun, 15 Sep 2019 09:50:28 -0700 Subject: Return and pass more appropriate types for backends --- alc/alc.cpp | 9 +++++---- alc/backends/alsa.cpp | 38 +++++++++++++++++++------------------- alc/backends/base.cpp | 6 +++--- alc/backends/base.h | 7 ++++--- alc/backends/coreaudio.cpp | 38 +++++++++++++++++++------------------- alc/backends/dsound.cpp | 28 ++++++++++++++-------------- alc/backends/jack.cpp | 22 +++++++++++----------- alc/backends/loopback.cpp | 12 ++++++------ alc/backends/null.cpp | 14 +++++++------- alc/backends/opensl.cpp | 36 +++++++++++++++++------------------- alc/backends/oss.cpp | 32 ++++++++++++++++---------------- alc/backends/portaudio.cpp | 30 +++++++++++++++--------------- alc/backends/pulseaudio.cpp | 24 ++++++++++++------------ alc/backends/qsa.cpp | 18 +++++++++--------- alc/backends/sdl2.cpp | 12 ++++++------ alc/backends/sndio.cpp | 36 ++++++++++++++++++------------------ alc/backends/solaris.cpp | 20 ++++++++++---------- alc/backends/wasapi.cpp | 22 +++++++++++----------- alc/backends/wave.cpp | 16 ++++++++-------- alc/backends/winmm.cpp | 34 +++++++++++++++++----------------- 20 files changed, 227 insertions(+), 227 deletions(-) (limited to 'alc/backends/alsa.cpp') diff --git a/alc/alc.cpp b/alc/alc.cpp index fa88cba8..4a4ed677 100644 --- a/alc/alc.cpp +++ b/alc/alc.cpp @@ -1920,7 +1920,7 @@ static ALCenum UpdateDeviceParams(ALCdevice *device, const ALCint *attrList) device->UpdateSize, device->BufferSize); try { - if(device->Backend->reset() == ALC_FALSE) + if(device->Backend->reset() == false) return ALC_INVALID_DEVICE; } catch(std::exception &e) { @@ -2235,7 +2235,7 @@ static ALCenum UpdateDeviceParams(ALCdevice *device, const ALCint *attrList) if(!device->Flags.get()) { - if(device->Backend->start() == ALC_FALSE) + if(device->Backend->start() == false) return ALC_INVALID_DEVICE; device->Flags.set(); } @@ -3911,7 +3911,8 @@ START_API_FUNC { std::lock_guard _{dev->StateLock}; BackendBase *backend{dev->Backend.get()}; if(samples >= 0 && backend->availableSamples() >= static_cast(samples)) - err = backend->captureSamples(buffer, static_cast(samples)); + err = backend->captureSamples(static_cast(buffer), + static_cast(samples)); } if(err != ALC_NO_ERROR) alcSetError(dev.get(), err); @@ -4085,7 +4086,7 @@ START_API_FUNC if(dev->mContexts.load()->empty()) return; - if(dev->Backend->start() == ALC_FALSE) + if(dev->Backend->start() == false) { aluHandleDisconnect(dev.get(), "Device start failure"); alcSetError(dev.get(), ALC_INVALID_DEVICE); diff --git a/alc/backends/alsa.cpp b/alc/backends/alsa.cpp index b797c768..da928171 100644 --- a/alc/backends/alsa.cpp +++ b/alc/backends/alsa.cpp @@ -395,8 +395,8 @@ struct AlsaPlayback final : public BackendBase { int mixerNoMMapProc(); ALCenum open(const ALCchar *name) override; - ALCboolean reset() override; - ALCboolean start() override; + bool reset() override; + bool start() override; void stop() override; ClockLatency getClockLatency() override; @@ -630,7 +630,7 @@ ALCenum AlsaPlayback::open(const ALCchar *name) return ALC_NO_ERROR; } -ALCboolean AlsaPlayback::reset() +bool AlsaPlayback::reset() { snd_pcm_format_t format{SND_PCM_FORMAT_UNKNOWN}; switch(mDevice->FmtType) @@ -770,16 +770,16 @@ ALCboolean AlsaPlayback::reset() SetDefaultChannelOrder(mDevice); - return ALC_TRUE; + return true; error: ERR("%s failed: %s\n", funcerr, snd_strerror(err)); if(hp) snd_pcm_hw_params_free(hp); if(sp) snd_pcm_sw_params_free(sp); - return ALC_FALSE; + return false; } -ALCboolean AlsaPlayback::start() +bool AlsaPlayback::start() { snd_pcm_hw_params_t *hp{}; snd_pcm_access_t access; @@ -797,7 +797,7 @@ ALCboolean AlsaPlayback::start() error: ERR("%s failed: %s\n", funcerr, snd_strerror(err)); if(hp) snd_pcm_hw_params_free(hp); - return ALC_FALSE; + return false; } snd_pcm_hw_params_free(hp); hp = nullptr; @@ -815,7 +815,7 @@ ALCboolean AlsaPlayback::start() if(err < 0) { ERR("snd_pcm_prepare(data->mPcmHandle) failed: %s\n", snd_strerror(err)); - return ALC_FALSE; + return false; } thread_func = &AlsaPlayback::mixerProc; } @@ -823,7 +823,7 @@ ALCboolean AlsaPlayback::start() try { mKillNow.store(false, std::memory_order_release); mThread = std::thread{std::mem_fn(thread_func), this}; - return ALC_TRUE; + return true; } catch(std::exception& e) { ERR("Could not create playback thread: %s\n", e.what()); @@ -831,7 +831,7 @@ ALCboolean AlsaPlayback::start() catch(...) { } mBuffer.clear(); - return ALC_FALSE; + return false; } void AlsaPlayback::stop() @@ -869,9 +869,9 @@ struct AlsaCapture final : public BackendBase { ~AlsaCapture() override; ALCenum open(const ALCchar *name) override; - ALCboolean start() override; + bool start() override; void stop() override; - ALCenum captureSamples(ALCvoid *buffer, ALCuint samples) override; + ALCenum captureSamples(al::byte *buffer, ALCuint samples) override; ALCuint availableSamples() override; ClockLatency getClockLatency() override; @@ -1015,7 +1015,7 @@ error2: } -ALCboolean AlsaCapture::start() +bool AlsaCapture::start() { int err{snd_pcm_prepare(mPcmHandle)}; if(err < 0) @@ -1029,11 +1029,11 @@ ALCboolean AlsaCapture::start() if(err < 0) { aluHandleDisconnect(mDevice, "Capture state failure: %s", snd_strerror(err)); - return ALC_FALSE; + return false; } mDoCapture = true; - return ALC_TRUE; + return true; } void AlsaCapture::stop() @@ -1058,7 +1058,7 @@ void AlsaCapture::stop() mDoCapture = false; } -ALCenum AlsaCapture::captureSamples(ALCvoid *buffer, ALCuint samples) +ALCenum AlsaCapture::captureSamples(al::byte *buffer, ALCuint samples) { if(mRing) { @@ -1078,7 +1078,7 @@ ALCenum AlsaCapture::captureSamples(ALCvoid *buffer, ALCuint samples) if(static_cast(amt) > samples) amt = samples; amt = snd_pcm_frames_to_bytes(mPcmHandle, amt); - std::copy_n(mBuffer.begin(), amt, static_cast(buffer)); + std::copy_n(mBuffer.begin(), amt, buffer); mBuffer.erase(mBuffer.begin(), mBuffer.begin()+amt); amt = snd_pcm_bytes_to_frames(mPcmHandle, amt); @@ -1111,11 +1111,11 @@ ALCenum AlsaCapture::captureSamples(ALCvoid *buffer, ALCuint samples) continue; } - buffer = static_cast(buffer) + amt; + buffer = buffer + amt; samples -= static_cast(amt); } if(samples > 0) - std::fill_n(static_cast(buffer), snd_pcm_frames_to_bytes(mPcmHandle, samples), + std::fill_n(buffer, snd_pcm_frames_to_bytes(mPcmHandle, samples), al::byte((mDevice->FmtType == DevFmtUByte) ? 0x80 : 0)); return ALC_NO_ERROR; diff --git a/alc/backends/base.cpp b/alc/backends/base.cpp index c4c6052b..a5f66606 100644 --- a/alc/backends/base.cpp +++ b/alc/backends/base.cpp @@ -28,10 +28,10 @@ BackendBase::BackendBase(ALCdevice *device) noexcept : mDevice{device} BackendBase::~BackendBase() = default; -ALCboolean BackendBase::reset() -{ return ALC_FALSE; } +bool BackendBase::reset() +{ return false; } -ALCenum BackendBase::captureSamples(void*, ALCuint) +ALCenum BackendBase::captureSamples(al::byte*, ALCuint) { return ALC_INVALID_DEVICE; } ALCuint BackendBase::availableSamples() diff --git a/alc/backends/base.h b/alc/backends/base.h index e88734dc..cc33ba50 100644 --- a/alc/backends/base.h +++ b/alc/backends/base.h @@ -9,6 +9,7 @@ #include "AL/alc.h" #include "alcmain.h" +#include "albyte.h" struct ClockLatency { @@ -33,11 +34,11 @@ ClockLatency GetClockLatency(ALCdevice *device); struct BackendBase { virtual ALCenum open(const ALCchar *name) = 0; - virtual ALCboolean reset(); - virtual ALCboolean start() = 0; + virtual bool reset(); + virtual bool start() = 0; virtual void stop() = 0; - virtual ALCenum captureSamples(void *buffer, ALCuint samples); + virtual ALCenum captureSamples(al::byte *buffer, ALCuint samples); virtual ALCuint availableSamples(); virtual ClockLatency getClockLatency(); diff --git a/alc/backends/coreaudio.cpp b/alc/backends/coreaudio.cpp index 3ae9800c..72754718 100644 --- a/alc/backends/coreaudio.cpp +++ b/alc/backends/coreaudio.cpp @@ -54,8 +54,8 @@ struct CoreAudioPlayback final : public BackendBase { AudioBufferList *ioData); ALCenum open(const ALCchar *name) override; - ALCboolean reset() override; - ALCboolean start() override; + bool reset() override; + bool start() override; void stop() override; AudioUnit mAudioUnit; @@ -137,7 +137,7 @@ ALCenum CoreAudioPlayback::open(const ALCchar *name) return ALC_NO_ERROR; } -ALCboolean CoreAudioPlayback::reset() +bool CoreAudioPlayback::reset() { OSStatus err{AudioUnitUninitialize(mAudioUnit)}; if(err != noErr) @@ -151,7 +151,7 @@ ALCboolean CoreAudioPlayback::reset() if(err != noErr || size != sizeof(AudioStreamBasicDescription)) { ERR("AudioUnitGetProperty failed\n"); - return ALC_FALSE; + return false; } #if 0 @@ -170,7 +170,7 @@ ALCboolean CoreAudioPlayback::reset() if(err != noErr) { ERR("AudioUnitSetProperty failed\n"); - return ALC_FALSE; + return false; } if(mDevice->Frequency != streamFormat.mSampleRate) @@ -254,7 +254,7 @@ ALCboolean CoreAudioPlayback::reset() if(err != noErr) { ERR("AudioUnitSetProperty failed\n"); - return ALC_FALSE; + return false; } /* setup callback */ @@ -268,7 +268,7 @@ ALCboolean CoreAudioPlayback::reset() if(err != noErr) { ERR("AudioUnitSetProperty failed\n"); - return ALC_FALSE; + return false; } /* init the default audio unit... */ @@ -276,21 +276,21 @@ ALCboolean CoreAudioPlayback::reset() if(err != noErr) { ERR("AudioUnitInitialize failed\n"); - return ALC_FALSE; + return false; } - return ALC_TRUE; + return true; } -ALCboolean CoreAudioPlayback::start() +bool CoreAudioPlayback::start() { OSStatus err{AudioOutputUnitStart(mAudioUnit)}; if(err != noErr) { ERR("AudioOutputUnitStart failed\n"); - return ALC_FALSE; + return false; } - return ALC_TRUE; + return true; } void CoreAudioPlayback::stop() @@ -313,9 +313,9 @@ struct CoreAudioCapture final : public BackendBase { UInt32 inNumberFrames, AudioBufferList *ioData); ALCenum open(const ALCchar *name) override; - ALCboolean start() override; + bool start() override; void stop() override; - ALCenum captureSamples(void *buffer, ALCuint samples) override; + ALCenum captureSamples(al::byte *buffer, ALCuint samples) override; ALCuint availableSamples() override; AudioUnit mAudioUnit{0}; @@ -628,15 +628,15 @@ ALCenum CoreAudioCapture::open(const ALCchar *name) } -ALCboolean CoreAudioCapture::start() +bool CoreAudioCapture::start() { OSStatus err{AudioOutputUnitStart(mAudioUnit)}; if(err != noErr) { ERR("AudioOutputUnitStart failed\n"); - return ALC_FALSE; + return false; } - return ALC_TRUE; + return true; } void CoreAudioCapture::stop() @@ -646,7 +646,7 @@ void CoreAudioCapture::stop() ERR("AudioOutputUnitStop failed\n"); } -ALCenum CoreAudioCapture::captureSamples(void *buffer, ALCuint samples) +ALCenum CoreAudioCapture::captureSamples(al::byte *buffer, ALCuint samples) { if(!mConverter) { @@ -663,7 +663,7 @@ ALCenum CoreAudioCapture::captureSamples(void *buffer, ALCuint samples) { const void *src1{rec_vec.second.buf}; auto src1len = static_cast(rec_vec.second.len); - got += mConverter->convert(&src1, &src1len, static_cast(buffer)+got, samples-got); + got += mConverter->convert(&src1, &src1len, buffer+got, samples-got); total_read += rec_vec.second.len - src1len; } diff --git a/alc/backends/dsound.cpp b/alc/backends/dsound.cpp index f9184968..c581fe8f 100644 --- a/alc/backends/dsound.cpp +++ b/alc/backends/dsound.cpp @@ -167,8 +167,8 @@ struct DSoundPlayback final : public BackendBase { int mixerProc(); ALCenum open(const ALCchar *name) override; - ALCboolean reset() override; - ALCboolean start() override; + bool reset() override; + bool start() override; void stop() override; IDirectSound *mDS{nullptr}; @@ -348,7 +348,7 @@ ALCenum DSoundPlayback::open(const ALCchar *name) return ALC_NO_ERROR; } -ALCboolean DSoundPlayback::reset() +bool DSoundPlayback::reset() { if(mNotifies) mNotifies->Release(); @@ -558,28 +558,28 @@ retry_open: if(mPrimaryBuffer) mPrimaryBuffer->Release(); mPrimaryBuffer = nullptr; - return ALC_FALSE; + return false; } ResetEvent(mNotifyEvent); SetDefaultWFXChannelOrder(mDevice); - return ALC_TRUE; + return true; } -ALCboolean DSoundPlayback::start() +bool DSoundPlayback::start() { try { mKillNow.store(false, std::memory_order_release); mThread = std::thread{std::mem_fn(&DSoundPlayback::mixerProc), this}; - return ALC_TRUE; + return true; } catch(std::exception& e) { ERR("Failed to start mixing thread: %s\n", e.what()); } catch(...) { } - return ALC_FALSE; + return false; } void DSoundPlayback::stop() @@ -597,9 +597,9 @@ struct DSoundCapture final : public BackendBase { ~DSoundCapture() override; ALCenum open(const ALCchar *name) override; - ALCboolean start() override; + bool start() override; void stop() override; - ALCenum captureSamples(void *buffer, ALCuint samples) override; + ALCenum captureSamples(al::byte *buffer, ALCuint samples) override; ALCuint availableSamples() override; IDirectSoundCapture *mDSC{nullptr}; @@ -791,16 +791,16 @@ ALCenum DSoundCapture::open(const ALCchar *name) return ALC_NO_ERROR; } -ALCboolean DSoundCapture::start() +bool DSoundCapture::start() { HRESULT hr{mDSCbuffer->Start(DSCBSTART_LOOPING)}; if(FAILED(hr)) { ERR("start failed: 0x%08lx\n", hr); aluHandleDisconnect(mDevice, "Failure starting capture: 0x%lx", hr); - return ALC_FALSE; + return false; } - return ALC_TRUE; + return true; } void DSoundCapture::stop() @@ -813,7 +813,7 @@ void DSoundCapture::stop() } } -ALCenum DSoundCapture::captureSamples(void *buffer, ALCuint samples) +ALCenum DSoundCapture::captureSamples(al::byte *buffer, ALCuint samples) { mRing->read(buffer, samples); return ALC_NO_ERROR; diff --git a/alc/backends/jack.cpp b/alc/backends/jack.cpp index e1ae91f0..660ea933 100644 --- a/alc/backends/jack.cpp +++ b/alc/backends/jack.cpp @@ -162,8 +162,8 @@ struct JackPlayback final : public BackendBase { int mixerProc(); ALCenum open(const ALCchar *name) override; - ALCboolean reset() override; - ALCboolean start() override; + bool reset() override; + bool start() override; void stop() override; ClockLatency getClockLatency() override; @@ -359,7 +359,7 @@ ALCenum JackPlayback::open(const ALCchar *name) return ALC_NO_ERROR; } -ALCboolean JackPlayback::reset() +bool JackPlayback::reset() { std::for_each(std::begin(mPort), std::end(mPort), [this](jack_port_t *port) -> void @@ -395,7 +395,7 @@ ALCboolean JackPlayback::reset() if(bad_port != ports_end) { ERR("Not enough JACK ports available for %s output\n", DevFmtChannelsString(mDevice->FmtChans)); - if(bad_port == std::begin(mPort)) return ALC_FALSE; + if(bad_port == std::begin(mPort)) return false; if(bad_port == std::begin(mPort)+1) mDevice->FmtChans = DevFmtMono; @@ -416,20 +416,20 @@ ALCboolean JackPlayback::reset() if(!mRing) { ERR("Failed to allocate ringbuffer\n"); - return ALC_FALSE; + return false; } SetDefaultChannelOrder(mDevice); - return ALC_TRUE; + return true; } -ALCboolean JackPlayback::start() +bool JackPlayback::start() { if(jack_activate(mClient)) { ERR("Failed to activate client\n"); - return ALC_FALSE; + return false; } const char **ports{jack_get_ports(mClient, nullptr, nullptr, @@ -438,7 +438,7 @@ ALCboolean JackPlayback::start() { ERR("No physical playback ports found\n"); jack_deactivate(mClient); - return ALC_FALSE; + return false; } std::mismatch(std::begin(mPort), std::end(mPort), ports, [this](const jack_port_t *port, const char *pname) -> bool @@ -460,7 +460,7 @@ ALCboolean JackPlayback::start() try { mKillNow.store(false, std::memory_order_release); mThread = std::thread{std::mem_fn(&JackPlayback::mixerProc), this}; - return ALC_TRUE; + return true; } catch(std::exception& e) { ERR("Could not create playback thread: %s\n", e.what()); @@ -468,7 +468,7 @@ ALCboolean JackPlayback::start() catch(...) { } jack_deactivate(mClient); - return ALC_FALSE; + return false; } void JackPlayback::stop() diff --git a/alc/backends/loopback.cpp b/alc/backends/loopback.cpp index 4a1c641a..7edc2d40 100644 --- a/alc/backends/loopback.cpp +++ b/alc/backends/loopback.cpp @@ -32,8 +32,8 @@ struct LoopbackBackend final : public BackendBase { LoopbackBackend(ALCdevice *device) noexcept : BackendBase{device} { } ALCenum open(const ALCchar *name) override; - ALCboolean reset() override; - ALCboolean start() override; + bool reset() override; + bool start() override; void stop() override; DEF_NEWDEL(LoopbackBackend) @@ -46,14 +46,14 @@ ALCenum LoopbackBackend::open(const ALCchar *name) return ALC_NO_ERROR; } -ALCboolean LoopbackBackend::reset() +bool LoopbackBackend::reset() { SetDefaultWFXChannelOrder(mDevice); - return ALC_TRUE; + return true; } -ALCboolean LoopbackBackend::start() -{ return ALC_TRUE; } +bool LoopbackBackend::start() +{ return true; } void LoopbackBackend::stop() { } diff --git a/alc/backends/null.cpp b/alc/backends/null.cpp index ae58cb8b..b6b115f1 100644 --- a/alc/backends/null.cpp +++ b/alc/backends/null.cpp @@ -52,8 +52,8 @@ struct NullBackend final : public BackendBase { int mixerProc(); ALCenum open(const ALCchar *name) override; - ALCboolean reset() override; - ALCboolean start() override; + bool reset() override; + bool start() override; void stop() override; std::atomic mKillNow{true}; @@ -120,25 +120,25 @@ ALCenum NullBackend::open(const ALCchar *name) return ALC_NO_ERROR; } -ALCboolean NullBackend::reset() +bool NullBackend::reset() { SetDefaultWFXChannelOrder(mDevice); - return ALC_TRUE; + return true; } -ALCboolean NullBackend::start() +bool NullBackend::start() { try { mKillNow.store(false, std::memory_order_release); mThread = std::thread{std::mem_fn(&NullBackend::mixerProc), this}; - return ALC_TRUE; + return true; } catch(std::exception& e) { ERR("Failed to start mixing thread: %s\n", e.what()); } catch(...) { } - return ALC_FALSE; + return false; } void NullBackend::stop() diff --git a/alc/backends/opensl.cpp b/alc/backends/opensl.cpp index 3a2f455e..0f1d8a21 100644 --- a/alc/backends/opensl.cpp +++ b/alc/backends/opensl.cpp @@ -152,8 +152,8 @@ struct OpenSLPlayback final : public BackendBase { int mixerProc(); ALCenum open(const ALCchar *name) override; - ALCboolean reset() override; - ALCboolean start() override; + bool reset() override; + bool start() override; void stop() override; ClockLatency getClockLatency() override; @@ -347,7 +347,7 @@ ALCenum OpenSLPlayback::open(const ALCchar *name) return ALC_NO_ERROR; } -ALCboolean OpenSLPlayback::reset() +bool OpenSLPlayback::reset() { SLDataLocator_AndroidSimpleBufferQueue loc_bufq; SLDataLocator_OutputMix loc_outmix; @@ -518,13 +518,13 @@ ALCboolean OpenSLPlayback::reset() VCALL0(mBufferQueueObj,Destroy)(); mBufferQueueObj = nullptr; - return ALC_FALSE; + return false; } - return ALC_TRUE; + return true; } -ALCboolean OpenSLPlayback::start() +bool OpenSLPlayback::start() { mRing->reset(); @@ -533,23 +533,23 @@ ALCboolean OpenSLPlayback::start() &bufferQueue)}; PRINTERR(result, "bufferQueue->GetInterface"); if(SL_RESULT_SUCCESS != result) - return ALC_FALSE; + return false; result = VCALL(bufferQueue,RegisterCallback)(&OpenSLPlayback::processC, this); PRINTERR(result, "bufferQueue->RegisterCallback"); - if(SL_RESULT_SUCCESS != result) return ALC_FALSE; + if(SL_RESULT_SUCCESS != result) return false; try { mKillNow.store(false, std::memory_order_release); mThread = std::thread(std::mem_fn(&OpenSLPlayback::mixerProc), this); - return ALC_TRUE; + return true; } catch(std::exception& e) { ERR("Could not create playback thread: %s\n", e.what()); } catch(...) { } - return ALC_FALSE; + return false; } void OpenSLPlayback::stop() @@ -615,9 +615,9 @@ struct OpenSLCapture final : public BackendBase { void process(SLAndroidSimpleBufferQueueItf bq); ALCenum open(const ALCchar *name) override; - ALCboolean start() override; + bool start() override; void stop() override; - ALCenum captureSamples(void *buffer, ALCuint samples) override; + ALCenum captureSamples(al::byte *buffer, ALCuint samples) override; ALCuint availableSamples() override; /* engine interfaces */ @@ -815,7 +815,7 @@ ALCenum OpenSLCapture::open(const ALCchar* name) return ALC_NO_ERROR; } -ALCboolean OpenSLCapture::start() +bool OpenSLCapture::start() { SLRecordItf record; SLresult result{VCALL(mRecordObj,GetInterface)(SL_IID_RECORD, &record)}; @@ -830,10 +830,10 @@ ALCboolean OpenSLCapture::start() if(SL_RESULT_SUCCESS != result) { aluHandleDisconnect(mDevice, "Failed to start capture: 0x%08x", result); - return ALC_FALSE; + return false; } - return ALC_TRUE; + return true; } void OpenSLCapture::stop() @@ -849,7 +849,7 @@ void OpenSLCapture::stop() } } -ALCenum OpenSLCapture::captureSamples(void *buffer, ALCuint samples) +ALCenum OpenSLCapture::captureSamples(al::byte *buffer, ALCuint samples) { ALuint chunk_size{mDevice->UpdateSize * mFrameSize}; SLAndroidSimpleBufferQueueItf bufferQueue; @@ -866,9 +866,7 @@ ALCenum OpenSLCapture::captureSamples(void *buffer, ALCuint samples) for(i = 0;i < samples;) { ALCuint rem{minu(samples - i, mDevice->UpdateSize - mSplOffset)}; - memcpy(static_cast(buffer) + i*mFrameSize, - data.first.buf + mSplOffset*mFrameSize, - rem * mFrameSize); + memcpy(buffer + i*mFrameSize, data.first.buf + mSplOffset*mFrameSize, rem*mFrameSize); mSplOffset += rem; if(mSplOffset == mDevice->UpdateSize) diff --git a/alc/backends/oss.cpp b/alc/backends/oss.cpp index ffdf3c23..c825ce3e 100644 --- a/alc/backends/oss.cpp +++ b/alc/backends/oss.cpp @@ -249,8 +249,8 @@ struct OSSPlayback final : public BackendBase { int mixerProc(); ALCenum open(const ALCchar *name) override; - ALCboolean reset() override; - ALCboolean start() override; + bool reset() override; + bool start() override; void stop() override; int mFd{-1}; @@ -359,7 +359,7 @@ ALCenum OSSPlayback::open(const ALCchar *name) return ALC_NO_ERROR; } -ALCboolean OSSPlayback::reset() +bool OSSPlayback::reset() { int ossFormat{}; switch(mDevice->FmtType) @@ -406,7 +406,7 @@ ALCboolean OSSPlayback::reset() { err: ERR("%s failed: %s\n", err, strerror(errno)); - return ALC_FALSE; + return false; } #undef CHECKERR @@ -414,7 +414,7 @@ ALCboolean OSSPlayback::reset() { ERR("Failed to set %s, got %d channels instead\n", DevFmtChannelsString(mDevice->FmtChans), numChannels); - return ALC_FALSE; + return false; } if(!((ossFormat == AFMT_S8 && mDevice->FmtType == DevFmtByte) || @@ -423,7 +423,7 @@ ALCboolean OSSPlayback::reset() { ERR("Failed to set %s samples, got OSS format %#x\n", DevFmtTypeString(mDevice->FmtType), ossFormat); - return ALC_FALSE; + return false; } mDevice->Frequency = ossSpeed; @@ -434,22 +434,22 @@ ALCboolean OSSPlayback::reset() mMixData.resize(mDevice->UpdateSize * mDevice->frameSizeFromFmt()); - return ALC_TRUE; + return true; } -ALCboolean OSSPlayback::start() +bool OSSPlayback::start() { try { mKillNow.store(false, std::memory_order_release); mThread = std::thread{std::mem_fn(&OSSPlayback::mixerProc), this}; - return ALC_TRUE; + return true; } catch(std::exception& e) { ERR("Could not create playback thread: %s\n", e.what()); } catch(...) { } - return ALC_FALSE; + return false; } void OSSPlayback::stop() @@ -470,9 +470,9 @@ struct OSScapture final : public BackendBase { int recordProc(); ALCenum open(const ALCchar *name) override; - ALCboolean start() override; + bool start() override; void stop() override; - ALCenum captureSamples(ALCvoid *buffer, ALCuint samples) override; + ALCenum captureSamples(al::byte *buffer, ALCuint samples) override; ALCuint availableSamples() override; int mFd{-1}; @@ -646,19 +646,19 @@ ALCenum OSScapture::open(const ALCchar *name) return ALC_NO_ERROR; } -ALCboolean OSScapture::start() +bool OSScapture::start() { try { mKillNow.store(false, std::memory_order_release); mThread = std::thread{std::mem_fn(&OSScapture::recordProc), this}; - return ALC_TRUE; + return true; } catch(std::exception& e) { ERR("Could not create record thread: %s\n", e.what()); } catch(...) { } - return ALC_FALSE; + return false; } void OSScapture::stop() @@ -671,7 +671,7 @@ void OSScapture::stop() ERR("Error resetting device: %s\n", strerror(errno)); } -ALCenum OSScapture::captureSamples(ALCvoid *buffer, ALCuint samples) +ALCenum OSScapture::captureSamples(al::byte *buffer, ALCuint samples) { mRing->read(buffer, samples); return ALC_NO_ERROR; diff --git a/alc/backends/portaudio.cpp b/alc/backends/portaudio.cpp index 4704a806..0b77f622 100644 --- a/alc/backends/portaudio.cpp +++ b/alc/backends/portaudio.cpp @@ -81,8 +81,8 @@ struct PortPlayback final : public BackendBase { const PaStreamCallbackTimeInfo *timeInfo, const PaStreamCallbackFlags statusFlags); ALCenum open(const ALCchar *name) override; - ALCboolean reset() override; - ALCboolean start() override; + bool reset() override; + bool start() override; void stop() override; PaStream *mStream{nullptr}; @@ -179,7 +179,7 @@ retry_open: } -ALCboolean PortPlayback::reset() +bool PortPlayback::reset() { const PaStreamInfo *streamInfo{Pa_GetStreamInfo(mStream)}; mDevice->Frequency = static_cast(streamInfo->sampleRate); @@ -198,7 +198,7 @@ ALCboolean PortPlayback::reset() else { ERR("Unexpected sample format: 0x%lx\n", mParams.sampleFormat); - return ALC_FALSE; + return false; } if(mParams.channelCount == 2) @@ -208,22 +208,22 @@ ALCboolean PortPlayback::reset() else { ERR("Unexpected channel count: %u\n", mParams.channelCount); - return ALC_FALSE; + return false; } SetDefaultChannelOrder(mDevice); - return ALC_TRUE; + return true; } -ALCboolean PortPlayback::start() +bool PortPlayback::start() { PaError err{Pa_StartStream(mStream)}; if(err != paNoError) { ERR("Pa_StartStream() returned an error: %s\n", Pa_GetErrorText(err)); - return ALC_FALSE; + return false; } - return ALC_TRUE; + return true; } void PortPlayback::stop() @@ -245,9 +245,9 @@ struct PortCapture final : public BackendBase { const PaStreamCallbackTimeInfo *timeInfo, const PaStreamCallbackFlags statusFlags); ALCenum open(const ALCchar *name) override; - ALCboolean start() override; + bool start() override; void stop() override; - ALCenum captureSamples(ALCvoid *buffer, ALCuint samples) override; + ALCenum captureSamples(al::byte *buffer, ALCuint samples) override; ALCuint availableSamples() override; PaStream *mStream{nullptr}; @@ -341,15 +341,15 @@ ALCenum PortCapture::open(const ALCchar *name) } -ALCboolean PortCapture::start() +bool PortCapture::start() { PaError err{Pa_StartStream(mStream)}; if(err != paNoError) { ERR("Error starting stream: %s\n", Pa_GetErrorText(err)); - return ALC_FALSE; + return false; } - return ALC_TRUE; + return true; } void PortCapture::stop() @@ -363,7 +363,7 @@ void PortCapture::stop() ALCuint PortCapture::availableSamples() { return static_cast(mRing->readSpace()); } -ALCenum PortCapture::captureSamples(ALCvoid *buffer, ALCuint samples) +ALCenum PortCapture::captureSamples(al::byte *buffer, ALCuint samples) { mRing->read(buffer, samples); return ALC_NO_ERROR; diff --git a/alc/backends/pulseaudio.cpp b/alc/backends/pulseaudio.cpp index 23d4e71a..e9997013 100644 --- a/alc/backends/pulseaudio.cpp +++ b/alc/backends/pulseaudio.cpp @@ -666,8 +666,8 @@ struct PulsePlayback final : public BackendBase { void streamMovedCallback(pa_stream *stream); ALCenum open(const ALCchar *name) override; - ALCboolean reset() override; - ALCboolean start() override; + bool reset() override; + bool start() override; void stop() override; ClockLatency getClockLatency() override; void lock() override; @@ -879,7 +879,7 @@ ALCenum PulsePlayback::open(const ALCchar *name) return ALC_NO_ERROR; } -ALCboolean PulsePlayback::reset() +bool PulsePlayback::reset() { std::unique_lock plock{pulse_lock}; @@ -1032,10 +1032,10 @@ ALCboolean PulsePlayback::reset() len, mAttr.prebuf, mDevice->BufferSize); } - return ALC_TRUE; + return true; } -ALCboolean PulsePlayback::start() +bool PulsePlayback::start() { std::unique_lock plock{pulse_lock}; @@ -1043,7 +1043,7 @@ ALCboolean PulsePlayback::start() pa_operation *op{pa_stream_cork(mStream, 0, stream_success_callback, nullptr)}; wait_for_operation(op, plock); - return ALC_TRUE; + return true; } void PulsePlayback::stop() @@ -1110,9 +1110,9 @@ struct PulseCapture final : public BackendBase { void streamMovedCallback(pa_stream *stream); ALCenum open(const ALCchar *name) override; - ALCboolean start() override; + bool start() override; void stop() override; - ALCenum captureSamples(ALCvoid *buffer, ALCuint samples) override; + ALCenum captureSamples(al::byte *buffer, ALCuint samples) override; ALCuint availableSamples() override; ClockLatency getClockLatency() override; void lock() override; @@ -1303,12 +1303,12 @@ ALCenum PulseCapture::open(const ALCchar *name) return ALC_NO_ERROR; } -ALCboolean PulseCapture::start() +bool PulseCapture::start() { std::unique_lock plock{pulse_lock}; pa_operation *op{pa_stream_cork(mStream, 0, stream_success_callback, nullptr)}; wait_for_operation(op, plock); - return ALC_TRUE; + return true; } void PulseCapture::stop() @@ -1318,9 +1318,9 @@ void PulseCapture::stop() wait_for_operation(op, plock); } -ALCenum PulseCapture::captureSamples(ALCvoid *buffer, ALCuint samples) +ALCenum PulseCapture::captureSamples(al::byte *buffer, ALCuint samples) { - al::span dstbuf{static_cast(buffer), samples * pa_frame_size(&mSpec)}; + al::span dstbuf{buffer, samples * pa_frame_size(&mSpec)}; /* Capture is done in fragment-sized chunks, so we loop until we get all * that's available */ diff --git a/alc/backends/qsa.cpp b/alc/backends/qsa.cpp index 64ed53aa..5fee2989 100644 --- a/alc/backends/qsa.cpp +++ b/alc/backends/qsa.cpp @@ -175,8 +175,8 @@ struct PlaybackWrapper final : public BackendBase { ~PlaybackWrapper() override; ALCenum open(const ALCchar *name) override; - ALCboolean reset() override; - ALCboolean start() override; + bool reset() override; + bool start() override; void stop() override; std::unique_ptr mExtraData; @@ -616,10 +616,10 @@ PlaybackWrapper::~PlaybackWrapper() ALCenum PlaybackWrapper::open(const ALCchar *name) { return qsa_open_playback(this, name); } -ALCboolean PlaybackWrapper::reset() +bool PlaybackWrapper::reset() { return qsa_reset_playback(this); } -ALCboolean PlaybackWrapper::start() +bool PlaybackWrapper::start() { return qsa_start_playback(this); } void PlaybackWrapper::stop() @@ -635,9 +635,9 @@ struct CaptureWrapper final : public BackendBase { ~CaptureWrapper() override; ALCenum open(const ALCchar *name) override; - ALCboolean start() override; + bool start() override; void stop() override; - ALCenum captureSamples(void *buffer, ALCuint samples) override; + ALCenum captureSamples(al::byte *buffer, ALCuint samples) override; ALCuint availableSamples() override; std::unique_ptr mExtraData; @@ -894,13 +894,13 @@ CaptureWrapper::~CaptureWrapper() ALCenum CaptureWrapper::open(const ALCchar *name) { return qsa_open_capture(this, name); } -ALCboolean CaptureWrapper::start() -{ qsa_start_capture(this); return ALC_TRUE; } +bool CaptureWrapper::start() +{ qsa_start_capture(this); return true; } void CaptureWrapper::stop() { qsa_stop_capture(this); } -ALCenum CaptureWrapper::captureSamples(void *buffer, ALCuint samples) +ALCenum CaptureWrapper::captureSamples(al::byte *buffer, ALCuint samples) { return qsa_capture_samples(this, buffer, samples); } ALCuint CaptureWrapper::availableSamples() diff --git a/alc/backends/sdl2.cpp b/alc/backends/sdl2.cpp index 6af0ac9d..71616906 100644 --- a/alc/backends/sdl2.cpp +++ b/alc/backends/sdl2.cpp @@ -55,8 +55,8 @@ struct Sdl2Backend final : public BackendBase { void audioCallback(Uint8 *stream, int len); ALCenum open(const ALCchar *name) override; - ALCboolean reset() override; - ALCboolean start() override; + bool reset() override; + bool start() override; void stop() override; void lock() override; void unlock() override; @@ -163,7 +163,7 @@ ALCenum Sdl2Backend::open(const ALCchar *name) return ALC_NO_ERROR; } -ALCboolean Sdl2Backend::reset() +bool Sdl2Backend::reset() { mDevice->Frequency = mFrequency; mDevice->FmtChans = mFmtChans; @@ -171,13 +171,13 @@ ALCboolean Sdl2Backend::reset() mDevice->UpdateSize = mUpdateSize; mDevice->BufferSize = mUpdateSize * 2; SetDefaultWFXChannelOrder(mDevice); - return ALC_TRUE; + return true; } -ALCboolean Sdl2Backend::start() +bool Sdl2Backend::start() { SDL_PauseAudioDevice(mDeviceID, 0); - return ALC_TRUE; + return true; } void Sdl2Backend::stop() diff --git a/alc/backends/sndio.cpp b/alc/backends/sndio.cpp index 4a470e82..d2654853 100644 --- a/alc/backends/sndio.cpp +++ b/alc/backends/sndio.cpp @@ -50,8 +50,8 @@ struct SndioPlayback final : public BackendBase { int mixerProc(); ALCenum open(const ALCchar *name) override; - ALCboolean reset() override; - ALCboolean start() override; + bool reset() override; + bool start() override; void stop() override; sio_hdl *mSndHandle{nullptr}; @@ -124,7 +124,7 @@ ALCenum SndioPlayback::open(const ALCchar *name) return ALC_NO_ERROR; } -ALCboolean SndioPlayback::reset() +bool SndioPlayback::reset() { sio_par par; sio_initpar(&par); @@ -169,13 +169,13 @@ ALCboolean SndioPlayback::reset() if(!sio_setpar(mSndHandle, &par) || !sio_getpar(mSndHandle, &par)) { ERR("Failed to set device parameters\n"); - return ALC_FALSE; + return false; } if(par.bits != par.bps*8) { ERR("Padded samples not supported (%u of %u bits)\n", par.bits, par.bps*8); - return ALC_FALSE; + return true; } mDevice->Frequency = par.rate; @@ -196,7 +196,7 @@ ALCboolean SndioPlayback::reset() else { ERR("Unhandled sample format: %s %u-bit\n", (par.sig?"signed":"unsigned"), par.bits); - return ALC_FALSE; + return false; } SetDefaultChannelOrder(mDevice); @@ -207,21 +207,21 @@ ALCboolean SndioPlayback::reset() mBuffer.resize(mDevice->UpdateSize * mDevice->frameSizeFromFmt()); std::fill(mBuffer.begin(), mBuffer.end(), 0); - return ALC_TRUE; + return true; } -ALCboolean SndioPlayback::start() +bool SndioPlayback::start() { if(!sio_start(mSndHandle)) { ERR("Error starting playback\n"); - return ALC_FALSE; + return false; } try { mKillNow.store(false, std::memory_order_release); mThread = std::thread{std::mem_fn(&SndioPlayback::mixerProc), this}; - return ALC_TRUE; + return true; } catch(std::exception& e) { ERR("Could not create playback thread: %s\n", e.what()); @@ -229,7 +229,7 @@ ALCboolean SndioPlayback::start() catch(...) { } sio_stop(mSndHandle); - return ALC_FALSE; + return false; } void SndioPlayback::stop() @@ -250,9 +250,9 @@ struct SndioCapture final : public BackendBase { int recordProc(); ALCenum open(const ALCchar *name) override; - ALCboolean start() override; + bool start() override; void stop() override; - ALCenum captureSamples(void *buffer, ALCuint samples) override; + ALCenum captureSamples(al::byte *buffer, ALCuint samples) override; ALCuint availableSamples() override; sio_hdl *mSndHandle{nullptr}; @@ -417,18 +417,18 @@ ALCenum SndioCapture::open(const ALCchar *name) return ALC_NO_ERROR; } -ALCboolean SndioCapture::start() +bool SndioCapture::start() { if(!sio_start(mSndHandle)) { ERR("Error starting playback\n"); - return ALC_FALSE; + return false; } try { mKillNow.store(false, std::memory_order_release); mThread = std::thread{std::mem_fn(&SndioCapture::recordProc), this}; - return ALC_TRUE; + return true; } catch(std::exception& e) { ERR("Could not create record thread: %s\n", e.what()); @@ -436,7 +436,7 @@ ALCboolean SndioCapture::start() catch(...) { } sio_stop(mSndHandle); - return ALC_FALSE; + return false; } void SndioCapture::stop() @@ -449,7 +449,7 @@ void SndioCapture::stop() ERR("Error stopping device\n"); } -ALCenum SndioCapture::captureSamples(void *buffer, ALCuint samples) +ALCenum SndioCapture::captureSamples(al::byte *buffer, ALCuint samples) { mRing->read(buffer, samples); return ALC_NO_ERROR; diff --git a/alc/backends/solaris.cpp b/alc/backends/solaris.cpp index 2e8fe458..128924bb 100644 --- a/alc/backends/solaris.cpp +++ b/alc/backends/solaris.cpp @@ -62,8 +62,8 @@ struct SolarisBackend final : public BackendBase { int mixerProc(); ALCenum open(const ALCchar *name) override; - ALCboolean reset() override; - ALCboolean start() override; + bool reset() override; + bool start() override; void stop() override; int mFd{-1}; @@ -160,7 +160,7 @@ ALCenum SolarisBackend::open(const ALCchar *name) return ALC_NO_ERROR; } -ALCboolean SolarisBackend::reset() +bool SolarisBackend::reset() { audio_info_t info; AUDIO_INITINFO(&info); @@ -200,14 +200,14 @@ ALCboolean SolarisBackend::reset() if(ioctl(mFd, AUDIO_SETINFO, &info) < 0) { ERR("ioctl failed: %s\n", strerror(errno)); - return ALC_FALSE; + return false; } if(mDevice->channelsFromFmt() != info.play.channels) { ERR("Failed to set %s, got %u channels instead\n", DevFmtChannelsString(mDevice->FmtChans), info.play.channels); - return ALC_FALSE; + return false; } if(!((info.play.precision == 8 && info.play.encoding == AUDIO_ENCODING_LINEAR8 && mDevice->FmtType == DevFmtUByte) || @@ -217,7 +217,7 @@ ALCboolean SolarisBackend::reset() { ERR("Could not set %s samples, got %d (0x%x)\n", DevFmtTypeString(mDevice->FmtType), info.play.precision, info.play.encoding); - return ALC_FALSE; + return false; } mDevice->Frequency = info.play.sample_rate; @@ -229,22 +229,22 @@ ALCboolean SolarisBackend::reset() mBuffer.resize(mDevice->UpdateSize * mDevice->frameSizeFromFmt()); std::fill(mBuffer.begin(), mBuffer.end(), 0); - return ALC_TRUE; + return true; } -ALCboolean SolarisBackend::start() +bool SolarisBackend::start() { try { mKillNow.store(false, std::memory_order_release); mThread = std::thread{std::mem_fn(&SolarisBackend::mixerProc), this}; - return ALC_TRUE; + return true; } catch(std::exception& e) { ERR("Could not create playback thread: %s\n", e.what()); } catch(...) { } - return ALC_FALSE; + return false; } void SolarisBackend::stop() diff --git a/alc/backends/wasapi.cpp b/alc/backends/wasapi.cpp index 0d04d5a7..0dec5cb9 100644 --- a/alc/backends/wasapi.cpp +++ b/alc/backends/wasapi.cpp @@ -614,9 +614,9 @@ struct WasapiPlayback final : public BackendBase, WasapiProxy { HRESULT openProxy() override; void closeProxy() override; - ALCboolean reset() override; + bool reset() override; HRESULT resetProxy() override; - ALCboolean start() override; + bool start() override; HRESULT startProxy() override; void stop() override; void stopProxy() override; @@ -812,10 +812,10 @@ void WasapiPlayback::closeProxy() } -ALCboolean WasapiPlayback::reset() +bool WasapiPlayback::reset() { HRESULT hr{pushMessage(MsgType::ResetDevice).get()}; - return SUCCEEDED(hr) ? ALC_TRUE : ALC_FALSE; + return SUCCEEDED(hr) ? true : false; } HRESULT WasapiPlayback::resetProxy() @@ -1073,10 +1073,10 @@ HRESULT WasapiPlayback::resetProxy() } -ALCboolean WasapiPlayback::start() +bool WasapiPlayback::start() { HRESULT hr{pushMessage(MsgType::StartDevice).get()}; - return SUCCEEDED(hr) ? ALC_TRUE : ALC_FALSE; + return SUCCEEDED(hr) ? true : false; } HRESULT WasapiPlayback::startProxy() @@ -1156,12 +1156,12 @@ struct WasapiCapture final : public BackendBase, WasapiProxy { void closeProxy() override; HRESULT resetProxy() override; - ALCboolean start() override; + bool start() override; HRESULT startProxy() override; void stop() override; void stopProxy() override; - ALCenum captureSamples(void *buffer, ALCuint samples) override; + ALCenum captureSamples(al::byte *buffer, ALCuint samples) override; ALCuint availableSamples() override; std::wstring mDevId; @@ -1622,10 +1622,10 @@ HRESULT WasapiCapture::resetProxy() } -ALCboolean WasapiCapture::start() +bool WasapiCapture::start() { HRESULT hr{pushMessage(MsgType::StartDevice).get()}; - return SUCCEEDED(hr) ? ALC_TRUE : ALC_FALSE; + return SUCCEEDED(hr) ? true : false; } HRESULT WasapiCapture::startProxy() @@ -1687,7 +1687,7 @@ void WasapiCapture::stopProxy() ALCuint WasapiCapture::availableSamples() { return static_cast(mRing->readSpace()); } -ALCenum WasapiCapture::captureSamples(void *buffer, ALCuint samples) +ALCenum WasapiCapture::captureSamples(al::byte *buffer, ALCuint samples) { mRing->read(buffer, samples); return ALC_NO_ERROR; diff --git a/alc/backends/wave.cpp b/alc/backends/wave.cpp index 41d0a880..797a9fa5 100644 --- a/alc/backends/wave.cpp +++ b/alc/backends/wave.cpp @@ -97,8 +97,8 @@ struct WaveBackend final : public BackendBase { int mixerProc(); ALCenum open(const ALCchar *name) override; - ALCboolean reset() override; - ALCboolean start() override; + bool reset() override; + bool start() override; void stop() override; FILE *mFile{nullptr}; @@ -231,7 +231,7 @@ ALCenum WaveBackend::open(const ALCchar *name) return ALC_NO_ERROR; } -ALCboolean WaveBackend::reset() +bool WaveBackend::reset() { ALuint channels=0, bytes=0, chanmask=0; int isbformat = 0; @@ -324,7 +324,7 @@ ALCboolean WaveBackend::reset() if(ferror(mFile)) { ERR("Error writing header: %s\n", strerror(errno)); - return ALC_FALSE; + return false; } mDataStart = ftell(mFile); @@ -333,22 +333,22 @@ ALCboolean WaveBackend::reset() const ALuint bufsize{mDevice->frameSizeFromFmt() * mDevice->UpdateSize}; mBuffer.resize(bufsize); - return ALC_TRUE; + return true; } -ALCboolean WaveBackend::start() +bool WaveBackend::start() { try { mKillNow.store(false, std::memory_order_release); mThread = std::thread{std::mem_fn(&WaveBackend::mixerProc), this}; - return ALC_TRUE; + return true; } catch(std::exception& e) { ERR("Failed to start mixing thread: %s\n", e.what()); } catch(...) { } - return ALC_FALSE; + return false; } void WaveBackend::stop() diff --git a/alc/backends/winmm.cpp b/alc/backends/winmm.cpp index 30a19e13..41c110d7 100644 --- a/alc/backends/winmm.cpp +++ b/alc/backends/winmm.cpp @@ -132,8 +132,8 @@ struct WinMMPlayback final : public BackendBase { int mixerProc(); ALCenum open(const ALCchar *name) override; - ALCboolean reset() override; - ALCboolean start() override; + bool reset() override; + bool start() override; void stop() override; std::atomic mWritable{0u}; @@ -263,7 +263,7 @@ retry_open: return ALC_NO_ERROR; } -ALCboolean WinMMPlayback::reset() +bool WinMMPlayback::reset() { mDevice->BufferSize = static_cast(uint64_t{mDevice->BufferSize} * mFormat.nSamplesPerSec / mDevice->Frequency); @@ -278,7 +278,7 @@ ALCboolean WinMMPlayback::reset() else { ERR("Unhandled IEEE float sample depth: %d\n", mFormat.wBitsPerSample); - return ALC_FALSE; + return false; } } else if(mFormat.wFormatTag == WAVE_FORMAT_PCM) @@ -290,13 +290,13 @@ ALCboolean WinMMPlayback::reset() else { ERR("Unhandled PCM sample depth: %d\n", mFormat.wBitsPerSample); - return ALC_FALSE; + return false; } } else { ERR("Unhandled format tag: 0x%04x\n", mFormat.wFormatTag); - return ALC_FALSE; + return false; } if(mFormat.nChannels == 2) @@ -306,7 +306,7 @@ ALCboolean WinMMPlayback::reset() else { ERR("Unhandled channel count: %d\n", mFormat.nChannels); - return ALC_FALSE; + return false; } SetDefaultWFXChannelOrder(mDevice); @@ -324,10 +324,10 @@ ALCboolean WinMMPlayback::reset() } mIdx = 0; - return ALC_TRUE; + return true; } -ALCboolean WinMMPlayback::start() +bool WinMMPlayback::start() { try { std::for_each(mWaveBuffer.begin(), mWaveBuffer.end(), @@ -338,14 +338,14 @@ ALCboolean WinMMPlayback::start() mKillNow.store(false, std::memory_order_release); mThread = std::thread{std::mem_fn(&WinMMPlayback::mixerProc), this}; - return ALC_TRUE; + return true; } catch(std::exception& e) { ERR("Failed to start mixing thread: %s\n", e.what()); } catch(...) { } - return ALC_FALSE; + return false; } void WinMMPlayback::stop() @@ -374,9 +374,9 @@ struct WinMMCapture final : public BackendBase { int captureProc(); ALCenum open(const ALCchar *name) override; - ALCboolean start() override; + bool start() override; void stop() override; - ALCenum captureSamples(void *buffer, ALCuint samples) override; + ALCenum captureSamples(al::byte *buffer, ALCuint samples) override; ALCuint availableSamples() override; std::atomic mReadable{0u}; @@ -543,7 +543,7 @@ ALCenum WinMMCapture::open(const ALCchar *name) return ALC_NO_ERROR; } -ALCboolean WinMMCapture::start() +bool WinMMCapture::start() { try { for(size_t i{0};i < mWaveBuffer.size();++i) @@ -556,14 +556,14 @@ ALCboolean WinMMCapture::start() mThread = std::thread{std::mem_fn(&WinMMCapture::captureProc), this}; waveInStart(mInHdl); - return ALC_TRUE; + return true; } catch(std::exception& e) { ERR("Failed to start mixing thread: %s\n", e.what()); } catch(...) { } - return ALC_FALSE; + return false; } void WinMMCapture::stop() @@ -585,7 +585,7 @@ void WinMMCapture::stop() mIdx = 0; } -ALCenum WinMMCapture::captureSamples(void *buffer, ALCuint samples) +ALCenum WinMMCapture::captureSamples(al::byte *buffer, ALCuint samples) { mRing->read(buffer, samples); return ALC_NO_ERROR; -- cgit v1.2.3 From 02d80cd74dd7b4517550af2f4ea22c409323a1d9 Mon Sep 17 00:00:00 2001 From: Chris Robinson Date: Mon, 7 Oct 2019 21:37:56 -0700 Subject: Use exceptions for backend open failures --- alc/alc.cpp | 32 +++------ alc/backends/alsa.cpp | 35 ++++------ alc/backends/base.cpp | 3 +- alc/backends/base.h | 2 +- alc/backends/coreaudio.cpp | 165 ++++++++++++++++++++++---------------------- alc/backends/dsound.cpp | 122 ++++++++++++++------------------ alc/backends/jack.cpp | 23 +++--- alc/backends/loopback.cpp | 5 +- alc/backends/null.cpp | 9 ++- alc/backends/opensl.cpp | 120 ++++++++++++++++---------------- alc/backends/oss.cpp | 70 +++++++++---------- alc/backends/portaudio.cpp | 129 ++++++++++++++++------------------ alc/backends/pulseaudio.cpp | 96 ++++++++++++-------------- alc/backends/qsa.cpp | 25 +++++-- alc/backends/sdl2.cpp | 50 +++++++------- alc/backends/sndio.cpp | 85 ++++++++++++----------- alc/backends/solaris.cpp | 11 +-- alc/backends/wasapi.cpp | 25 ++++--- alc/backends/wave.cpp | 14 ++-- alc/backends/winmm.cpp | 67 +++++++++--------- 20 files changed, 524 insertions(+), 564 deletions(-) (limited to 'alc/backends/alsa.cpp') diff --git a/alc/alc.cpp b/alc/alc.cpp index 119067fd..025395fe 100644 --- a/alc/alc.cpp +++ b/alc/alc.cpp @@ -3548,16 +3548,9 @@ START_API_FUNC device->NumAuxSends = DEFAULT_SENDS; try { - /* Create the device backend. */ - device->Backend = PlaybackFactory->createBackend(device.get(), BackendType::Playback); - - /* Find a playback device to open */ - ALCenum err{device->Backend->open(deviceName)}; - if(err != ALC_NO_ERROR) - { - alcSetError(nullptr, err); - return nullptr; - } + auto backend = PlaybackFactory->createBackend(device.get(), BackendType::Playback); + backend->open(deviceName); + device->Backend = std::move(backend); } catch(al::backend_exception &e) { WARN("Failed to open playback device: %s\n", e.what()); @@ -3811,17 +3804,13 @@ START_API_FUNC device->BufferSize = static_cast(samples); try { - device->Backend = CaptureFactory->createBackend(device.get(), BackendType::Capture); - TRACE("Capture format: %s, %s, %uhz, %u / %u buffer\n", DevFmtChannelsString(device->FmtChans), DevFmtTypeString(device->FmtType), device->Frequency, device->UpdateSize, device->BufferSize); - ALCenum err{device->Backend->open(deviceName)}; - if(err != ALC_NO_ERROR) - { - alcSetError(nullptr, err); - return nullptr; - } + + auto backend = CaptureFactory->createBackend(device.get(), BackendType::Capture); + backend->open(deviceName); + device->Backend = std::move(backend); } catch(al::backend_exception &e) { WARN("Failed to open capture device: %s\n", e.what()); @@ -4000,11 +3989,10 @@ START_API_FUNC device->NumMonoSources = device->SourcesMax - device->NumStereoSources; try { - device->Backend = LoopbackBackendFactory::getFactory().createBackend(device.get(), + auto backend = LoopbackBackendFactory::getFactory().createBackend(device.get(), BackendType::Playback); - - // Open the "backend" - device->Backend->open("Loopback"); + backend->open("Loopback"); + device->Backend = std::move(backend); } catch(al::backend_exception &e) { WARN("Failed to open loopback device: %s\n", e.what()); diff --git a/alc/backends/alsa.cpp b/alc/backends/alsa.cpp index da928171..2e157602 100644 --- a/alc/backends/alsa.cpp +++ b/alc/backends/alsa.cpp @@ -40,6 +40,7 @@ #include "albyte.h" #include "alcmain.h" #include "alconfig.h" +#include "alexcpt.h" #include "almalloc.h" #include "alnumeric.h" #include "aloptional.h" @@ -394,7 +395,7 @@ struct AlsaPlayback final : public BackendBase { int mixerProc(); int mixerNoMMapProc(); - ALCenum open(const ALCchar *name) override; + void open(const ALCchar *name) override; bool reset() override; bool start() override; void stop() override; @@ -592,7 +593,7 @@ int AlsaPlayback::mixerNoMMapProc() } -ALCenum AlsaPlayback::open(const ALCchar *name) +void AlsaPlayback::open(const ALCchar *name) { const char *driver{}; if(name) @@ -605,7 +606,7 @@ ALCenum AlsaPlayback::open(const ALCchar *name) { return entry.name == name; } ); if(iter == PlaybackDevices.cend()) - return ALC_INVALID_VALUE; + throw al::backend_exception{ALC_INVALID_VALUE, "Device name \"%s\" not found", name}; driver = iter->device_name.c_str(); } else @@ -619,15 +620,14 @@ ALCenum AlsaPlayback::open(const ALCchar *name) if(err < 0) { ERR("Could not open playback device '%s': %s\n", driver, snd_strerror(err)); - return ALC_OUT_OF_MEMORY; + throw al::backend_exception{ALC_OUT_OF_MEMORY, "Could not open ALSA playback \"%s\"", + driver}; } /* Free alsa's global config tree. Otherwise valgrind reports a ton of leaks. */ snd_config_update_free_global(); mDevice->DeviceName = name; - - return ALC_NO_ERROR; } bool AlsaPlayback::reset() @@ -868,7 +868,7 @@ struct AlsaCapture final : public BackendBase { AlsaCapture(ALCdevice *device) noexcept : BackendBase{device} { } ~AlsaCapture() override; - ALCenum open(const ALCchar *name) override; + void open(const ALCchar *name) override; bool start() override; void stop() override; ALCenum captureSamples(al::byte *buffer, ALCuint samples) override; @@ -895,7 +895,7 @@ AlsaCapture::~AlsaCapture() } -ALCenum AlsaCapture::open(const ALCchar *name) +void AlsaCapture::open(const ALCchar *name) { const char *driver{}; if(name) @@ -908,7 +908,7 @@ ALCenum AlsaCapture::open(const ALCchar *name) { return entry.name == name; } ); if(iter == CaptureDevices.cend()) - return ALC_INVALID_VALUE; + throw al::backend_exception{ALC_INVALID_VALUE, "Device name \"%s\" not found", name}; driver = iter->device_name.c_str(); } else @@ -922,7 +922,8 @@ ALCenum AlsaCapture::open(const ALCchar *name) if(err < 0) { ERR("Could not open capture device '%s': %s\n", driver, snd_strerror(err)); - return ALC_INVALID_VALUE; + throw al::backend_exception{ALC_OUT_OF_MEMORY, "Could not open ALSA capture \"%s\"", + driver}; } /* Free alsa's global config tree. Otherwise valgrind reports a ton of leaks. */ @@ -994,24 +995,16 @@ ALCenum AlsaCapture::open(const ALCchar *name) if(!mRing) { ERR("ring buffer create failed\n"); - goto error2; + throw al::backend_exception{ALC_INVALID_VALUE, "Failed to create ring buffer"}; } } mDevice->DeviceName = name; - - return ALC_NO_ERROR; + return; error: - ERR("%s failed: %s\n", funcerr, snd_strerror(err)); if(hp) snd_pcm_hw_params_free(hp); - -error2: - mRing = nullptr; - snd_pcm_close(mPcmHandle); - mPcmHandle = nullptr; - - return ALC_INVALID_VALUE; + throw al::backend_exception{ALC_INVALID_VALUE, "%s failed: %s", funcerr, snd_strerror(err)}; } diff --git a/alc/backends/base.cpp b/alc/backends/base.cpp index a5f66606..4fce0a67 100644 --- a/alc/backends/base.cpp +++ b/alc/backends/base.cpp @@ -9,6 +9,7 @@ #include "AL/al.h" #include "alcmain.h" +#include "alexcpt.h" #include "alnumeric.h" #include "atomic.h" @@ -29,7 +30,7 @@ BackendBase::BackendBase(ALCdevice *device) noexcept : mDevice{device} BackendBase::~BackendBase() = default; bool BackendBase::reset() -{ return false; } +{ throw al::backend_exception{ALC_INVALID_VALUE, "Invalid BackendVase call"}; } ALCenum BackendBase::captureSamples(al::byte*, ALCuint) { return ALC_INVALID_DEVICE; } diff --git a/alc/backends/base.h b/alc/backends/base.h index 55240fd2..d4856818 100644 --- a/alc/backends/base.h +++ b/alc/backends/base.h @@ -32,7 +32,7 @@ inline std::chrono::nanoseconds GetDeviceClockTime(ALCdevice *device) ClockLatency GetClockLatency(ALCdevice *device); struct BackendBase { - virtual ALCenum open(const ALCchar *name) = 0; + virtual void open(const ALCchar *name) = 0; virtual bool reset(); virtual bool start() = 0; diff --git a/alc/backends/coreaudio.cpp b/alc/backends/coreaudio.cpp index 5d004efc..9254dbe0 100644 --- a/alc/backends/coreaudio.cpp +++ b/alc/backends/coreaudio.cpp @@ -27,6 +27,7 @@ #include #include "alcmain.h" +#include "alexcpt.h" #include "alu.h" #include "ringbuffer.h" #include "converter.h" @@ -48,17 +49,21 @@ struct CoreAudioPlayback final : public BackendBase { static OSStatus MixerProcC(void *inRefCon, AudioUnitRenderActionFlags *ioActionFlags, const AudioTimeStamp *inTimeStamp, UInt32 inBusNumber, UInt32 inNumberFrames, - AudioBufferList *ioData); + AudioBufferList *ioData) + { + return static_cast(inRefCon)->MixerProc(ioActionFlags, inTimeStamp, + inBusNumber, inNumberFrames, ioData); + } OSStatus MixerProc(AudioUnitRenderActionFlags *ioActionFlags, const AudioTimeStamp *inTimeStamp, UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList *ioData); - ALCenum open(const ALCchar *name) override; + void open(const ALCchar *name) override; bool reset() override; bool start() override; void stop() override; - AudioUnit mAudioUnit; + AudioUnit mAudioUnit{}; ALuint mFrameSize{0u}; AudioStreamBasicDescription mFormat{}; // This is the OpenAL format as a CoreAudio ASBD @@ -73,14 +78,6 @@ CoreAudioPlayback::~CoreAudioPlayback() } -OSStatus CoreAudioPlayback::MixerProcC(void *inRefCon, - AudioUnitRenderActionFlags *ioActionFlags, const AudioTimeStamp *inTimeStamp, - UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList *ioData) -{ - return static_cast(inRefCon)->MixerProc(ioActionFlags, inTimeStamp, - inBusNumber, inNumberFrames, ioData); -} - OSStatus CoreAudioPlayback::MixerProc(AudioUnitRenderActionFlags*, const AudioTimeStamp*, UInt32, UInt32, AudioBufferList *ioData) { @@ -91,12 +88,12 @@ OSStatus CoreAudioPlayback::MixerProc(AudioUnitRenderActionFlags*, } -ALCenum CoreAudioPlayback::open(const ALCchar *name) +void CoreAudioPlayback::open(const ALCchar *name) { if(!name) name = ca_device; else if(strcmp(name, ca_device) != 0) - return ALC_INVALID_VALUE; + throw al::backend_exception{ALC_INVALID_VALUE, "Device name \"%s\" not found", name}; /* open the default output unit */ AudioComponentDescription desc{}; @@ -114,14 +111,15 @@ ALCenum CoreAudioPlayback::open(const ALCchar *name) if(comp == nullptr) { ERR("AudioComponentFindNext failed\n"); - return ALC_INVALID_VALUE; + throw al::backend_exception{ALC_INVALID_VALUE, "Could not find audio component"}; } OSStatus err{AudioComponentInstanceNew(comp, &mAudioUnit)}; if(err != noErr) { ERR("AudioComponentInstanceNew failed\n"); - return ALC_INVALID_VALUE; + throw al::backend_exception{ALC_INVALID_VALUE, "Could not create component instance: %u", + err}; } /* init and start the default audio unit... */ @@ -129,12 +127,10 @@ ALCenum CoreAudioPlayback::open(const ALCchar *name) if(err != noErr) { ERR("AudioUnitInitialize failed\n"); - AudioComponentInstanceDispose(mAudioUnit); - return ALC_INVALID_VALUE; + throw al::backend_exception{ALC_INVALID_VALUE, "Could not initialize audio unit: %u", err}; } mDevice->DeviceName = name; - return ALC_NO_ERROR; } bool CoreAudioPlayback::reset() @@ -307,12 +303,16 @@ struct CoreAudioCapture final : public BackendBase { static OSStatus RecordProcC(void *inRefCon, AudioUnitRenderActionFlags *ioActionFlags, const AudioTimeStamp *inTimeStamp, UInt32 inBusNumber, UInt32 inNumberFrames, - AudioBufferList *ioData); + AudioBufferList *ioData) + { + return static_cast(inRefCon)->RecordProc(ioActionFlags, inTimeStamp, + inBusNumber, inNumberFrames, ioData); + } OSStatus RecordProc(AudioUnitRenderActionFlags *ioActionFlags, const AudioTimeStamp *inTimeStamp, UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList *ioData); - ALCenum open(const ALCchar *name) override; + void open(const ALCchar *name) override; bool start() override; void stop() override; ALCenum captureSamples(al::byte *buffer, ALCuint samples) override; @@ -338,23 +338,15 @@ CoreAudioCapture::~CoreAudioCapture() } -OSStatus CoreAudioCapture::RecordProcC(void *inRefCon, - AudioUnitRenderActionFlags *ioActionFlags, const AudioTimeStamp *inTimeStamp, - UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList *ioData) -{ - return static_cast(inRefCon)->RecordProc(ioActionFlags, inTimeStamp, - inBusNumber, inNumberFrames, ioData); -} - OSStatus CoreAudioCapture::RecordProc(AudioUnitRenderActionFlags*, const AudioTimeStamp *inTimeStamp, UInt32, UInt32 inNumberFrames, AudioBufferList*) { AudioUnitRenderActionFlags flags = 0; union { - ALbyte _[sizeof(AudioBufferList) + sizeof(AudioBuffer)*2]; + al::byte _[sizeof(AudioBufferList) + sizeof(AudioBuffer)*2]; AudioBufferList list; - } audiobuf = { { 0 } }; + } audiobuf{}; auto rec_vec = mRing->getWriteVector(); inNumberFrames = static_cast(minz(inNumberFrames, @@ -393,7 +385,7 @@ OSStatus CoreAudioCapture::RecordProc(AudioUnitRenderActionFlags*, } -ALCenum CoreAudioCapture::open(const ALCchar *name) +void CoreAudioCapture::open(const ALCchar *name) { AudioStreamBasicDescription requestedFormat; // The application requested format AudioStreamBasicDescription hardwareFormat; // The hardware format @@ -412,7 +404,7 @@ ALCenum CoreAudioCapture::open(const ALCchar *name) if(!name) name = ca_device; else if(strcmp(name, ca_device) != 0) - return ALC_INVALID_VALUE; + throw al::backend_exception{ALC_INVALID_VALUE, "Device name \"%s\" not found", name}; desc.componentType = kAudioUnitType_Output; #if TARGET_OS_IOS @@ -429,7 +421,7 @@ ALCenum CoreAudioCapture::open(const ALCchar *name) if(comp == NULL) { ERR("AudioComponentFindNext failed\n"); - return ALC_INVALID_VALUE; + throw al::backend_exception{ALC_INVALID_VALUE, "Could not finda udio component"}; } // Open the component @@ -437,7 +429,8 @@ ALCenum CoreAudioCapture::open(const ALCchar *name) if(err != noErr) { ERR("AudioComponentInstanceNew failed\n"); - return ALC_INVALID_VALUE; + throw al::backend_exception{ALC_INVALID_VALUE, "Could not create component instance: %u", + err}; } // Turn off AudioUnit output @@ -447,7 +440,8 @@ ALCenum CoreAudioCapture::open(const ALCchar *name) if(err != noErr) { ERR("AudioUnitSetProperty failed\n"); - return ALC_INVALID_VALUE; + throw al::backend_exception{ALC_INVALID_VALUE, + "Could not disable audio unit output property: %u", err}; } // Turn on AudioUnit input @@ -457,7 +451,8 @@ ALCenum CoreAudioCapture::open(const ALCchar *name) if(err != noErr) { ERR("AudioUnitSetProperty failed\n"); - return ALC_INVALID_VALUE; + throw al::backend_exception{ALC_INVALID_VALUE, + "Could not enable audio unit input property: %u", err}; } #if !TARGET_OS_IOS @@ -470,16 +465,17 @@ ALCenum CoreAudioCapture::open(const ALCchar *name) propertyAddress.mScope = kAudioObjectPropertyScopeGlobal; propertyAddress.mElement = kAudioObjectPropertyElementMaster; - err = AudioObjectGetPropertyData(kAudioObjectSystemObject, &propertyAddress, 0, NULL, &propertySize, &inputDevice); + err = AudioObjectGetPropertyData(kAudioObjectSystemObject, &propertyAddress, 0, nullptr, + &propertySize, &inputDevice); if(err != noErr) { ERR("AudioObjectGetPropertyData failed\n"); - return ALC_INVALID_VALUE; + throw al::backend_exception{ALC_INVALID_VALUE, "Could not get input device: %u", err}; } if(inputDevice == kAudioDeviceUnknown) { ERR("No input device found\n"); - return ALC_INVALID_VALUE; + throw al::backend_exception{ALC_INVALID_VALUE, "Unknown input device"}; } // Track the input device @@ -488,7 +484,7 @@ ALCenum CoreAudioCapture::open(const ALCchar *name) if(err != noErr) { ERR("AudioUnitSetProperty failed\n"); - return ALC_INVALID_VALUE; + throw al::backend_exception{ALC_INVALID_VALUE, "Could not set input device: %u", err}; } } #endif @@ -502,7 +498,7 @@ ALCenum CoreAudioCapture::open(const ALCchar *name) if(err != noErr) { ERR("AudioUnitSetProperty failed\n"); - return ALC_INVALID_VALUE; + throw al::backend_exception{ALC_INVALID_VALUE, "Could not set capture callback: %u", err}; } // Initialize the device @@ -510,7 +506,7 @@ ALCenum CoreAudioCapture::open(const ALCchar *name) if(err != noErr) { ERR("AudioUnitInitialize failed\n"); - return ALC_INVALID_VALUE; + throw al::backend_exception{ALC_INVALID_VALUE, "Could not initialize audio unit: %u", err}; } // Get the hardware format @@ -520,52 +516,54 @@ ALCenum CoreAudioCapture::open(const ALCchar *name) if(err != noErr || propertySize != sizeof(AudioStreamBasicDescription)) { ERR("AudioUnitGetProperty failed\n"); - return ALC_INVALID_VALUE; + throw al::backend_exception{ALC_INVALID_VALUE, "Could not get input format: %u", err}; } // Set up the requested format description switch(mDevice->FmtType) { - case DevFmtUByte: - requestedFormat.mBitsPerChannel = 8; - requestedFormat.mFormatFlags = kAudioFormatFlagIsPacked; - break; - case DevFmtShort: - requestedFormat.mBitsPerChannel = 16; - requestedFormat.mFormatFlags = kAudioFormatFlagIsSignedInteger | kAudioFormatFlagsNativeEndian | kAudioFormatFlagIsPacked; - break; - case DevFmtInt: - requestedFormat.mBitsPerChannel = 32; - requestedFormat.mFormatFlags = kAudioFormatFlagIsSignedInteger | kAudioFormatFlagsNativeEndian | kAudioFormatFlagIsPacked; - break; - case DevFmtFloat: - requestedFormat.mBitsPerChannel = 32; - requestedFormat.mFormatFlags = kAudioFormatFlagIsPacked; - break; - case DevFmtByte: - case DevFmtUShort: - case DevFmtUInt: - ERR("%s samples not supported\n", DevFmtTypeString(mDevice->FmtType)); - return ALC_INVALID_VALUE; + case DevFmtUByte: + requestedFormat.mBitsPerChannel = 8; + requestedFormat.mFormatFlags = kAudioFormatFlagIsPacked; + break; + case DevFmtShort: + requestedFormat.mBitsPerChannel = 16; + requestedFormat.mFormatFlags = kAudioFormatFlagIsSignedInteger | kAudioFormatFlagsNativeEndian | kAudioFormatFlagIsPacked; + break; + case DevFmtInt: + requestedFormat.mBitsPerChannel = 32; + requestedFormat.mFormatFlags = kAudioFormatFlagIsSignedInteger | kAudioFormatFlagsNativeEndian | kAudioFormatFlagIsPacked; + break; + case DevFmtFloat: + requestedFormat.mBitsPerChannel = 32; + requestedFormat.mFormatFlags = kAudioFormatFlagIsPacked; + break; + case DevFmtByte: + case DevFmtUShort: + case DevFmtUInt: + ERR("%s samples not supported\n", DevFmtTypeString(mDevice->FmtType)); + throw al::backend_exception{ALC_INVALID_VALUE, "%s samples not suppoted", + DevFmtTypeString(mDevice->FmtType)}; } switch(mDevice->FmtChans) { - case DevFmtMono: - requestedFormat.mChannelsPerFrame = 1; - break; - case DevFmtStereo: - requestedFormat.mChannelsPerFrame = 2; - break; + case DevFmtMono: + requestedFormat.mChannelsPerFrame = 1; + break; + case DevFmtStereo: + requestedFormat.mChannelsPerFrame = 2; + break; - case DevFmtQuad: - case DevFmtX51: - case DevFmtX51Rear: - case DevFmtX61: - case DevFmtX71: - case DevFmtAmbi3D: - ERR("%s not supported\n", DevFmtChannelsString(mDevice->FmtChans)); - return ALC_INVALID_VALUE; + case DevFmtQuad: + case DevFmtX51: + case DevFmtX51Rear: + case DevFmtX61: + case DevFmtX71: + case DevFmtAmbi3D: + ERR("%s not supported\n", DevFmtChannelsString(mDevice->FmtChans)); + throw al::backend_exception{ALC_INVALID_VALUE, "%s not supported", + DevFmtChannelsString(mDevice->FmtChans)}; } requestedFormat.mBytesPerFrame = requestedFormat.mChannelsPerFrame * requestedFormat.mBitsPerChannel / 8; @@ -591,7 +589,7 @@ ALCenum CoreAudioCapture::open(const ALCchar *name) if(err != noErr) { ERR("AudioUnitSetProperty failed\n"); - return ALC_INVALID_VALUE; + throw al::backend_exception{ALC_INVALID_VALUE, "Could not set input format: %u", err}; } // Set the AudioUnit output format frame count @@ -602,7 +600,8 @@ ALCenum CoreAudioCapture::open(const ALCchar *name) if(FrameCount64 > std::numeric_limits::max()/2) { ERR("FrameCount too large\n"); - return ALC_INVALID_VALUE; + throw al::backend_exception{ALC_INVALID_VALUE, + "Calculated frame count is too lareg: %" PRIu64, FrameCount64}; } outputFrameCount = static_cast(FrameCount64); @@ -611,7 +610,8 @@ ALCenum CoreAudioCapture::open(const ALCchar *name) if(err != noErr) { ERR("AudioUnitSetProperty failed: %d\n", err); - return ALC_INVALID_VALUE; + throw al::backend_exception{ALC_INVALID_VALUE, "Failed to set capture frame count: %u", + err}; } // Set up sample converter if needed @@ -621,10 +621,9 @@ ALCenum CoreAudioCapture::open(const ALCchar *name) mDevice->Frequency, Resampler::FastBSinc24); mRing = CreateRingBuffer(outputFrameCount, mFrameSize, false); - if(!mRing) return ALC_INVALID_VALUE; + if(!mRing) throw al::backend_exception{ALC_INVALID_VALUE, "Failed to allocate ring buffer"}; mDevice->DeviceName = name; - return ALC_NO_ERROR; } diff --git a/alc/backends/dsound.cpp b/alc/backends/dsound.cpp index c7014e33..19a3c604 100644 --- a/alc/backends/dsound.cpp +++ b/alc/backends/dsound.cpp @@ -45,6 +45,7 @@ #include #include "alcmain.h" +#include "alexcpt.h" #include "alu.h" #include "ringbuffer.h" #include "compat.h" @@ -166,7 +167,7 @@ struct DSoundPlayback final : public BackendBase { int mixerProc(); - ALCenum open(const ALCchar *name) override; + void open(const ALCchar *name) override; bool reset() override; bool start() override; void stop() override; @@ -298,7 +299,7 @@ FORCE_ALIGN int DSoundPlayback::mixerProc() return 0; } -ALCenum DSoundPlayback::open(const ALCchar *name) +void DSoundPlayback::open(const ALCchar *name) { HRESULT hr; if(PlaybackDevices.empty()) @@ -325,7 +326,7 @@ ALCenum DSoundPlayback::open(const ALCchar *name) { return entry.name == name; } ); if(iter == PlaybackDevices.cend()) - return ALC_INVALID_VALUE; + throw al::backend_exception{ALC_INVALID_VALUE, "Device name \"%s\" not found", name}; guid = &iter->guid; } @@ -341,11 +342,10 @@ ALCenum DSoundPlayback::open(const ALCchar *name) if(FAILED(hr)) { ERR("Device init failed: 0x%08lx\n", hr); - return ALC_INVALID_VALUE; + throw al::backend_exception{ALC_INVALID_VALUE, "Device init failed: 0x%08lx", hr}; } mDevice->DeviceName = name; - return ALC_NO_ERROR; } bool DSoundPlayback::reset() @@ -596,7 +596,7 @@ struct DSoundCapture final : public BackendBase { DSoundCapture(ALCdevice *device) noexcept : BackendBase{device} { } ~DSoundCapture() override; - ALCenum open(const ALCchar *name) override; + void open(const ALCchar *name) override; bool start() override; void stop() override; ALCenum captureSamples(al::byte *buffer, ALCuint samples) override; @@ -627,7 +627,7 @@ DSoundCapture::~DSoundCapture() } -ALCenum DSoundCapture::open(const ALCchar *name) +void DSoundCapture::open(const ALCchar *name) { HRESULT hr; if(CaptureDevices.empty()) @@ -654,79 +654,60 @@ ALCenum DSoundCapture::open(const ALCchar *name) { return entry.name == name; } ); if(iter == CaptureDevices.cend()) - return ALC_INVALID_VALUE; + throw al::backend_exception{ALC_INVALID_VALUE, "Device name \"%s\" not found", name}; guid = &iter->guid; } switch(mDevice->FmtType) { - case DevFmtByte: - case DevFmtUShort: - case DevFmtUInt: - WARN("%s capture samples not supported\n", DevFmtTypeString(mDevice->FmtType)); - return ALC_INVALID_ENUM; + case DevFmtByte: + case DevFmtUShort: + case DevFmtUInt: + WARN("%s capture samples not supported\n", DevFmtTypeString(mDevice->FmtType)); + throw al::backend_exception{ALC_INVALID_VALUE, "%s capture samples not supported", + DevFmtTypeString(mDevice->FmtType)}; - case DevFmtUByte: - case DevFmtShort: - case DevFmtInt: - case DevFmtFloat: - break; + case DevFmtUByte: + case DevFmtShort: + case DevFmtInt: + case DevFmtFloat: + break; } WAVEFORMATEXTENSIBLE InputType{}; switch(mDevice->FmtChans) { - case DevFmtMono: - InputType.dwChannelMask = SPEAKER_FRONT_CENTER; - break; - case DevFmtStereo: - InputType.dwChannelMask = SPEAKER_FRONT_LEFT | - SPEAKER_FRONT_RIGHT; - break; - case DevFmtQuad: - InputType.dwChannelMask = SPEAKER_FRONT_LEFT | - SPEAKER_FRONT_RIGHT | - SPEAKER_BACK_LEFT | - SPEAKER_BACK_RIGHT; - break; - case DevFmtX51: - InputType.dwChannelMask = SPEAKER_FRONT_LEFT | - SPEAKER_FRONT_RIGHT | - SPEAKER_FRONT_CENTER | - SPEAKER_LOW_FREQUENCY | - SPEAKER_SIDE_LEFT | - SPEAKER_SIDE_RIGHT; - break; - case DevFmtX51Rear: - InputType.dwChannelMask = SPEAKER_FRONT_LEFT | - SPEAKER_FRONT_RIGHT | - SPEAKER_FRONT_CENTER | - SPEAKER_LOW_FREQUENCY | - SPEAKER_BACK_LEFT | - SPEAKER_BACK_RIGHT; - break; - case DevFmtX61: - InputType.dwChannelMask = SPEAKER_FRONT_LEFT | - SPEAKER_FRONT_RIGHT | - SPEAKER_FRONT_CENTER | - SPEAKER_LOW_FREQUENCY | - SPEAKER_BACK_CENTER | - SPEAKER_SIDE_LEFT | - SPEAKER_SIDE_RIGHT; - break; - case DevFmtX71: - InputType.dwChannelMask = SPEAKER_FRONT_LEFT | - SPEAKER_FRONT_RIGHT | - SPEAKER_FRONT_CENTER | - SPEAKER_LOW_FREQUENCY | - SPEAKER_BACK_LEFT | - SPEAKER_BACK_RIGHT | - SPEAKER_SIDE_LEFT | - SPEAKER_SIDE_RIGHT; - break; - case DevFmtAmbi3D: - WARN("%s capture not supported\n", DevFmtChannelsString(mDevice->FmtChans)); - return ALC_INVALID_ENUM; + case DevFmtMono: + InputType.dwChannelMask = SPEAKER_FRONT_CENTER; + break; + case DevFmtStereo: + InputType.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT; + break; + case DevFmtQuad: + InputType.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_BACK_LEFT | + SPEAKER_BACK_RIGHT; + break; + case DevFmtX51: + InputType.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | + SPEAKER_LOW_FREQUENCY | SPEAKER_SIDE_LEFT | SPEAKER_SIDE_RIGHT; + break; + case DevFmtX51Rear: + InputType.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | + SPEAKER_LOW_FREQUENCY | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT; + break; + case DevFmtX61: + InputType.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | + SPEAKER_LOW_FREQUENCY | SPEAKER_BACK_CENTER | SPEAKER_SIDE_LEFT | SPEAKER_SIDE_RIGHT; + break; + case DevFmtX71: + InputType.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | + SPEAKER_LOW_FREQUENCY | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT | SPEAKER_SIDE_LEFT | + SPEAKER_SIDE_RIGHT; + break; + case DevFmtAmbi3D: + WARN("%s capture not supported\n", DevFmtChannelsString(mDevice->FmtChans)); + throw al::backend_exception{ALC_INVALID_VALUE, "%s capture not supported", + DevFmtChannelsString(mDevice->FmtChans)}; } InputType.Format.wFormatTag = WAVE_FORMAT_PCM; @@ -781,14 +762,13 @@ ALCenum DSoundCapture::open(const ALCchar *name) mDSC->Release(); mDSC = nullptr; - return ALC_INVALID_VALUE; + throw al::backend_exception{ALC_INVALID_VALUE, "Device init failed: 0x%08lx", hr}; } mBufferBytes = DSCBDescription.dwBufferBytes; SetDefaultWFXChannelOrder(mDevice); mDevice->DeviceName = name; - return ALC_NO_ERROR; } bool DSoundCapture::start() diff --git a/alc/backends/jack.cpp b/alc/backends/jack.cpp index 660ea933..c7e2839c 100644 --- a/alc/backends/jack.cpp +++ b/alc/backends/jack.cpp @@ -32,6 +32,7 @@ #include "alcmain.h" #include "alu.h" #include "alconfig.h" +#include "alexcpt.h" #include "dynload.h" #include "ringbuffer.h" #include "threads.h" @@ -153,15 +154,17 @@ struct JackPlayback final : public BackendBase { JackPlayback(ALCdevice *device) noexcept : BackendBase{device} { } ~JackPlayback() override; - static int bufferSizeNotifyC(jack_nframes_t numframes, void *arg); + static int bufferSizeNotifyC(jack_nframes_t numframes, void *arg) + { return static_cast(arg)->bufferSizeNotify(numframes); } int bufferSizeNotify(jack_nframes_t numframes); - static int processC(jack_nframes_t numframes, void *arg); + static int processC(jack_nframes_t numframes, void *arg) + { return static_cast(arg)->process(numframes); } int process(jack_nframes_t numframes); int mixerProc(); - ALCenum open(const ALCchar *name) override; + void open(const ALCchar *name) override; bool reset() override; bool start() override; void stop() override; @@ -194,9 +197,6 @@ JackPlayback::~JackPlayback() } -int JackPlayback::bufferSizeNotifyC(jack_nframes_t numframes, void *arg) -{ return static_cast(arg)->bufferSizeNotify(numframes); } - int JackPlayback::bufferSizeNotify(jack_nframes_t numframes) { std::lock_guard _{mDevice->StateLock}; @@ -221,9 +221,6 @@ int JackPlayback::bufferSizeNotify(jack_nframes_t numframes) } -int JackPlayback::processC(jack_nframes_t numframes, void *arg) -{ return static_cast(arg)->process(numframes); } - int JackPlayback::process(jack_nframes_t numframes) { jack_default_audio_sample_t *out[MAX_OUTPUT_CHANNELS]; @@ -329,12 +326,12 @@ int JackPlayback::mixerProc() } -ALCenum JackPlayback::open(const ALCchar *name) +void JackPlayback::open(const ALCchar *name) { if(!name) name = jackDevice; else if(strcmp(name, jackDevice) != 0) - return ALC_INVALID_VALUE; + throw al::backend_exception{ALC_INVALID_VALUE, "Device name \"%s\" not found", name}; const char *client_name{"alsoft"}; jack_status_t status; @@ -342,7 +339,8 @@ ALCenum JackPlayback::open(const ALCchar *name) if(mClient == nullptr) { ERR("jack_client_open() failed, status = 0x%02x\n", status); - return ALC_INVALID_VALUE; + throw al::backend_exception{ALC_INVALID_VALUE, "Failed to connect to JACK server: 0x%02x", + status}; } if((status&JackServerStarted)) TRACE("JACK server started\n"); @@ -356,7 +354,6 @@ ALCenum JackPlayback::open(const ALCchar *name) jack_set_buffer_size_callback(mClient, &JackPlayback::bufferSizeNotifyC, this); mDevice->DeviceName = name; - return ALC_NO_ERROR; } bool JackPlayback::reset() diff --git a/alc/backends/loopback.cpp b/alc/backends/loopback.cpp index 7edc2d40..511061f3 100644 --- a/alc/backends/loopback.cpp +++ b/alc/backends/loopback.cpp @@ -31,7 +31,7 @@ namespace { struct LoopbackBackend final : public BackendBase { LoopbackBackend(ALCdevice *device) noexcept : BackendBase{device} { } - ALCenum open(const ALCchar *name) override; + void open(const ALCchar *name) override; bool reset() override; bool start() override; void stop() override; @@ -40,10 +40,9 @@ struct LoopbackBackend final : public BackendBase { }; -ALCenum LoopbackBackend::open(const ALCchar *name) +void LoopbackBackend::open(const ALCchar *name) { mDevice->DeviceName = name; - return ALC_NO_ERROR; } bool LoopbackBackend::reset() diff --git a/alc/backends/null.cpp b/alc/backends/null.cpp index b6b115f1..aca59605 100644 --- a/alc/backends/null.cpp +++ b/alc/backends/null.cpp @@ -31,6 +31,7 @@ #include #include "alcmain.h" +#include "alexcpt.h" #include "almalloc.h" #include "alu.h" #include "logging.h" @@ -51,7 +52,7 @@ struct NullBackend final : public BackendBase { int mixerProc(); - ALCenum open(const ALCchar *name) override; + void open(const ALCchar *name) override; bool reset() override; bool start() override; void stop() override; @@ -108,16 +109,14 @@ int NullBackend::mixerProc() } -ALCenum NullBackend::open(const ALCchar *name) +void NullBackend::open(const ALCchar *name) { if(!name) name = nullDevice; else if(strcmp(name, nullDevice) != 0) - return ALC_INVALID_VALUE; + throw al::backend_exception{ALC_INVALID_VALUE, "Device name \"%s\" not found", name}; mDevice->DeviceName = name; - - return ALC_NO_ERROR; } bool NullBackend::reset() diff --git a/alc/backends/opensl.cpp b/alc/backends/opensl.cpp index 50ea884d..4e4ceb5b 100644 --- a/alc/backends/opensl.cpp +++ b/alc/backends/opensl.cpp @@ -28,10 +28,12 @@ #include #include +#include #include #include #include "alcmain.h" +#include "alexcpt.h" #include "alu.h" #include "compat.h" #include "endiantest.h" @@ -58,26 +60,24 @@ SLuint32 GetChannelMask(DevFmtChannels chans) { switch(chans) { - case DevFmtMono: return SL_SPEAKER_FRONT_CENTER; - case DevFmtStereo: return SL_SPEAKER_FRONT_LEFT|SL_SPEAKER_FRONT_RIGHT; - case DevFmtQuad: return SL_SPEAKER_FRONT_LEFT|SL_SPEAKER_FRONT_RIGHT| - SL_SPEAKER_BACK_LEFT|SL_SPEAKER_BACK_RIGHT; - case DevFmtX51: return SL_SPEAKER_FRONT_LEFT|SL_SPEAKER_FRONT_RIGHT| - SL_SPEAKER_FRONT_CENTER|SL_SPEAKER_LOW_FREQUENCY| - SL_SPEAKER_SIDE_LEFT|SL_SPEAKER_SIDE_RIGHT; - case DevFmtX51Rear: return SL_SPEAKER_FRONT_LEFT|SL_SPEAKER_FRONT_RIGHT| - SL_SPEAKER_FRONT_CENTER|SL_SPEAKER_LOW_FREQUENCY| - SL_SPEAKER_BACK_LEFT|SL_SPEAKER_BACK_RIGHT; - case DevFmtX61: return SL_SPEAKER_FRONT_LEFT|SL_SPEAKER_FRONT_RIGHT| - SL_SPEAKER_FRONT_CENTER|SL_SPEAKER_LOW_FREQUENCY| - SL_SPEAKER_BACK_CENTER| - SL_SPEAKER_SIDE_LEFT|SL_SPEAKER_SIDE_RIGHT; - case DevFmtX71: return SL_SPEAKER_FRONT_LEFT|SL_SPEAKER_FRONT_RIGHT| - SL_SPEAKER_FRONT_CENTER|SL_SPEAKER_LOW_FREQUENCY| - SL_SPEAKER_BACK_LEFT|SL_SPEAKER_BACK_RIGHT| - SL_SPEAKER_SIDE_LEFT|SL_SPEAKER_SIDE_RIGHT; - case DevFmtAmbi3D: - break; + case DevFmtMono: return SL_SPEAKER_FRONT_CENTER; + case DevFmtStereo: return SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT; + case DevFmtQuad: return SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT | + SL_SPEAKER_BACK_LEFT | SL_SPEAKER_BACK_RIGHT; + case DevFmtX51: return SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT | + SL_SPEAKER_FRONT_CENTER | SL_SPEAKER_LOW_FREQUENCY | SL_SPEAKER_SIDE_LEFT | + SL_SPEAKER_SIDE_RIGHT; + case DevFmtX51Rear: return SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT | + SL_SPEAKER_FRONT_CENTER | SL_SPEAKER_LOW_FREQUENCY | SL_SPEAKER_BACK_LEFT | + SL_SPEAKER_BACK_RIGHT; + case DevFmtX61: return SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT | + SL_SPEAKER_FRONT_CENTER | SL_SPEAKER_LOW_FREQUENCY | SL_SPEAKER_BACK_CENTER | + SL_SPEAKER_SIDE_LEFT | SL_SPEAKER_SIDE_RIGHT; + case DevFmtX71: return SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT | + SL_SPEAKER_FRONT_CENTER | SL_SPEAKER_LOW_FREQUENCY | SL_SPEAKER_BACK_LEFT | + SL_SPEAKER_BACK_RIGHT | SL_SPEAKER_SIDE_LEFT | SL_SPEAKER_SIDE_RIGHT; + case DevFmtAmbi3D: + break; } return 0; } @@ -87,16 +87,16 @@ SLuint32 GetTypeRepresentation(DevFmtType type) { switch(type) { - case DevFmtUByte: - case DevFmtUShort: - case DevFmtUInt: - return SL_ANDROID_PCM_REPRESENTATION_UNSIGNED_INT; - case DevFmtByte: - case DevFmtShort: - case DevFmtInt: - return SL_ANDROID_PCM_REPRESENTATION_SIGNED_INT; - case DevFmtFloat: - return SL_ANDROID_PCM_REPRESENTATION_FLOAT; + case DevFmtUByte: + case DevFmtUShort: + case DevFmtUInt: + return SL_ANDROID_PCM_REPRESENTATION_UNSIGNED_INT; + case DevFmtByte: + case DevFmtShort: + case DevFmtInt: + return SL_ANDROID_PCM_REPRESENTATION_SIGNED_INT; + case DevFmtFloat: + return SL_ANDROID_PCM_REPRESENTATION_FLOAT; } return 0; } @@ -106,31 +106,31 @@ const char *res_str(SLresult result) { switch(result) { - case SL_RESULT_SUCCESS: return "Success"; - case SL_RESULT_PRECONDITIONS_VIOLATED: return "Preconditions violated"; - case SL_RESULT_PARAMETER_INVALID: return "Parameter invalid"; - case SL_RESULT_MEMORY_FAILURE: return "Memory failure"; - case SL_RESULT_RESOURCE_ERROR: return "Resource error"; - case SL_RESULT_RESOURCE_LOST: return "Resource lost"; - case SL_RESULT_IO_ERROR: return "I/O error"; - case SL_RESULT_BUFFER_INSUFFICIENT: return "Buffer insufficient"; - case SL_RESULT_CONTENT_CORRUPTED: return "Content corrupted"; - case SL_RESULT_CONTENT_UNSUPPORTED: return "Content unsupported"; - case SL_RESULT_CONTENT_NOT_FOUND: return "Content not found"; - case SL_RESULT_PERMISSION_DENIED: return "Permission denied"; - case SL_RESULT_FEATURE_UNSUPPORTED: return "Feature unsupported"; - case SL_RESULT_INTERNAL_ERROR: return "Internal error"; - case SL_RESULT_UNKNOWN_ERROR: return "Unknown error"; - case SL_RESULT_OPERATION_ABORTED: return "Operation aborted"; - case SL_RESULT_CONTROL_LOST: return "Control lost"; + case SL_RESULT_SUCCESS: return "Success"; + case SL_RESULT_PRECONDITIONS_VIOLATED: return "Preconditions violated"; + case SL_RESULT_PARAMETER_INVALID: return "Parameter invalid"; + case SL_RESULT_MEMORY_FAILURE: return "Memory failure"; + case SL_RESULT_RESOURCE_ERROR: return "Resource error"; + case SL_RESULT_RESOURCE_LOST: return "Resource lost"; + case SL_RESULT_IO_ERROR: return "I/O error"; + case SL_RESULT_BUFFER_INSUFFICIENT: return "Buffer insufficient"; + case SL_RESULT_CONTENT_CORRUPTED: return "Content corrupted"; + case SL_RESULT_CONTENT_UNSUPPORTED: return "Content unsupported"; + case SL_RESULT_CONTENT_NOT_FOUND: return "Content not found"; + case SL_RESULT_PERMISSION_DENIED: return "Permission denied"; + case SL_RESULT_FEATURE_UNSUPPORTED: return "Feature unsupported"; + case SL_RESULT_INTERNAL_ERROR: return "Internal error"; + case SL_RESULT_UNKNOWN_ERROR: return "Unknown error"; + case SL_RESULT_OPERATION_ABORTED: return "Operation aborted"; + case SL_RESULT_CONTROL_LOST: return "Control lost"; #ifdef SL_RESULT_READONLY - case SL_RESULT_READONLY: return "ReadOnly"; + case SL_RESULT_READONLY: return "ReadOnly"; #endif #ifdef SL_RESULT_ENGINEOPTION_UNSUPPORTED - case SL_RESULT_ENGINEOPTION_UNSUPPORTED: return "Engine option unsupported"; + case SL_RESULT_ENGINEOPTION_UNSUPPORTED: return "Engine option unsupported"; #endif #ifdef SL_RESULT_SOURCE_SINK_INCOMPATIBLE - case SL_RESULT_SOURCE_SINK_INCOMPATIBLE: return "Source/Sink incompatible"; + case SL_RESULT_SOURCE_SINK_INCOMPATIBLE: return "Source/Sink incompatible"; #endif } return "Unknown error code"; @@ -152,7 +152,7 @@ struct OpenSLPlayback final : public BackendBase { int mixerProc(); - ALCenum open(const ALCchar *name) override; + void open(const ALCchar *name) override; bool reset() override; bool start() override; void stop() override; @@ -298,12 +298,12 @@ int OpenSLPlayback::mixerProc() } -ALCenum OpenSLPlayback::open(const ALCchar *name) +void OpenSLPlayback::open(const ALCchar *name) { if(!name) name = opensl_device; else if(strcmp(name, opensl_device) != 0) - return ALC_INVALID_VALUE; + throw al::backend_exception{ALC_INVALID_VALUE, "Device name \"%s\" not found", name}; // create engine SLresult result{slCreateEngine(&mEngineObj, 0, nullptr, 0, nullptr, nullptr)}; @@ -340,11 +340,11 @@ ALCenum OpenSLPlayback::open(const ALCchar *name) mEngineObj = nullptr; mEngine = nullptr; - return ALC_INVALID_VALUE; + throw al::backend_exception{ALC_INVALID_VALUE, "Failed to initialize OpenSL: 0x%08x", + result}; } mDevice->DeviceName = name; - return ALC_NO_ERROR; } bool OpenSLPlayback::reset() @@ -635,7 +635,7 @@ struct OpenSLCapture final : public BackendBase { { static_cast(context)->process(bq); } void process(SLAndroidSimpleBufferQueueItf bq); - ALCenum open(const ALCchar *name) override; + void open(const ALCchar *name) override; bool start() override; void stop() override; ALCenum captureSamples(al::byte *buffer, ALCuint samples) override; @@ -676,12 +676,12 @@ void OpenSLCapture::process(SLAndroidSimpleBufferQueueItf) } -ALCenum OpenSLCapture::open(const ALCchar* name) +void OpenSLCapture::open(const ALCchar* name) { if(!name) name = opensl_device; else if(strcmp(name, opensl_device) != 0) - return ALC_INVALID_VALUE; + throw al::backend_exception{ALC_INVALID_VALUE, "Device name \"%s\" not found", name}; SLresult result{slCreateEngine(&mEngineObj, 0, nullptr, 0, nullptr, nullptr)}; PRINTERR(result, "slCreateEngine"); @@ -841,11 +841,11 @@ ALCenum OpenSLCapture::open(const ALCchar* name) mEngineObj = nullptr; mEngine = nullptr; - return ALC_INVALID_VALUE; + throw al::backend_exception{ALC_INVALID_VALUE, "Failed to initialize OpenSL: 0x%08x", + result}; } mDevice->DeviceName = name; - return ALC_NO_ERROR; } bool OpenSLCapture::start() diff --git a/alc/backends/oss.cpp b/alc/backends/oss.cpp index c825ce3e..1e3ad28b 100644 --- a/alc/backends/oss.cpp +++ b/alc/backends/oss.cpp @@ -45,6 +45,7 @@ #include "alcmain.h" #include "alconfig.h" +#include "alexcpt.h" #include "almalloc.h" #include "alnumeric.h" #include "aloptional.h" @@ -248,7 +249,7 @@ struct OSSPlayback final : public BackendBase { int mixerProc(); - ALCenum open(const ALCchar *name) override; + void open(const ALCchar *name) override; bool reset() override; bool start() override; void stop() override; @@ -329,7 +330,7 @@ int OSSPlayback::mixerProc() } -ALCenum OSSPlayback::open(const ALCchar *name) +void OSSPlayback::open(const ALCchar *name) { const char *devname{DefaultPlayback.c_str()}; if(!name) @@ -344,7 +345,7 @@ ALCenum OSSPlayback::open(const ALCchar *name) { return entry.name == name; } ); if(iter == PlaybackDevices.cend()) - return ALC_INVALID_VALUE; + throw al::backend_exception{ALC_INVALID_VALUE, "Device name \"%s\" not found", name}; devname = iter->device_name.c_str(); } @@ -352,11 +353,11 @@ ALCenum OSSPlayback::open(const ALCchar *name) if(mFd == -1) { ERR("Could not open %s: %s\n", devname, strerror(errno)); - return ALC_INVALID_VALUE; + throw al::backend_exception{ALC_INVALID_VALUE, "Could not open %s: %s", devname, + strerror(errno)}; } mDevice->DeviceName = name; - return ALC_NO_ERROR; } bool OSSPlayback::reset() @@ -469,7 +470,7 @@ struct OSScapture final : public BackendBase { int recordProc(); - ALCenum open(const ALCchar *name) override; + void open(const ALCchar *name) override; bool start() override; void stop() override; ALCenum captureSamples(al::byte *buffer, ALCuint samples) override; @@ -539,7 +540,7 @@ int OSScapture::recordProc() } -ALCenum OSScapture::open(const ALCchar *name) +void OSScapture::open(const ALCchar *name) { const char *devname{DefaultCapture.c_str()}; if(!name) @@ -554,7 +555,7 @@ ALCenum OSScapture::open(const ALCchar *name) { return entry.name == name; } ); if(iter == CaptureDevices.cend()) - return ALC_INVALID_VALUE; + throw al::backend_exception{ALC_INVALID_VALUE, "Device name \"%s\" not found", name}; devname = iter->device_name.c_str(); } @@ -562,27 +563,29 @@ ALCenum OSScapture::open(const ALCchar *name) if(mFd == -1) { ERR("Could not open %s: %s\n", devname, strerror(errno)); - return ALC_INVALID_VALUE; + throw al::backend_exception{ALC_INVALID_VALUE, "Could not open %s: %s", devname, + strerror(errno)}; } int ossFormat{}; switch(mDevice->FmtType) { - case DevFmtByte: - ossFormat = AFMT_S8; - break; - case DevFmtUByte: - ossFormat = AFMT_U8; - break; - case DevFmtShort: - ossFormat = AFMT_S16_NE; - break; - case DevFmtUShort: - case DevFmtInt: - case DevFmtUInt: - case DevFmtFloat: - ERR("%s capture samples not supported\n", DevFmtTypeString(mDevice->FmtType)); - return ALC_INVALID_VALUE; + case DevFmtByte: + ossFormat = AFMT_S8; + break; + case DevFmtUByte: + ossFormat = AFMT_U8; + break; + case DevFmtShort: + ossFormat = AFMT_S16_NE; + break; + case DevFmtUShort: + case DevFmtInt: + case DevFmtUInt: + case DevFmtFloat: + ERR("%s capture samples not supported\n", DevFmtTypeString(mDevice->FmtType)); + throw al::backend_exception{ALC_INVALID_VALUE, "%s capture samples not supported", + DevFmtTypeString(mDevice->FmtType)}; } ALuint periods{4}; @@ -608,9 +611,7 @@ ALCenum OSScapture::open(const ALCchar *name) { err: ERR("%s failed: %s\n", err, strerror(errno)); - close(mFd); - mFd = -1; - return ALC_INVALID_VALUE; + throw al::backend_exception{ALC_INVALID_VALUE, "%s failed: %s", err, strerror(errno)}; } #undef CHECKERR @@ -618,9 +619,8 @@ ALCenum OSScapture::open(const ALCchar *name) { ERR("Failed to set %s, got %d channels instead\n", DevFmtChannelsString(mDevice->FmtChans), numChannels); - close(mFd); - mFd = -1; - return ALC_INVALID_VALUE; + throw al::backend_exception{ALC_INVALID_VALUE, "Failed to set %s capture", + DevFmtChannelsString(mDevice->FmtChans)}; } if(!((ossFormat == AFMT_S8 && mDevice->FmtType == DevFmtByte) || @@ -628,22 +628,18 @@ ALCenum OSScapture::open(const ALCchar *name) (ossFormat == AFMT_S16_NE && mDevice->FmtType == DevFmtShort))) { ERR("Failed to set %s samples, got OSS format %#x\n", DevFmtTypeString(mDevice->FmtType), ossFormat); - close(mFd); - mFd = -1; - return ALC_INVALID_VALUE; + throw al::backend_exception{ALC_INVALID_VALUE, "Failed to set %s samples", + DevFmtTypeString(mDevice->FmtType)}; } mRing = CreateRingBuffer(mDevice->BufferSize, frameSize, false); if(!mRing) { ERR("Ring buffer create failed\n"); - close(mFd); - mFd = -1; - return ALC_OUT_OF_MEMORY; + throw al::backend_exception{ALC_INVALID_VALUE, "Failed to create ring buffer"}; } mDevice->DeviceName = name; - return ALC_NO_ERROR; } bool OSScapture::start() diff --git a/alc/backends/portaudio.cpp b/alc/backends/portaudio.cpp index 0b77f622..7847f41d 100644 --- a/alc/backends/portaudio.cpp +++ b/alc/backends/portaudio.cpp @@ -27,6 +27,7 @@ #include #include "alcmain.h" +#include "alexcpt.h" #include "alu.h" #include "alconfig.h" #include "dynload.h" @@ -76,11 +77,15 @@ struct PortPlayback final : public BackendBase { static int writeCallbackC(const void *inputBuffer, void *outputBuffer, unsigned long framesPerBuffer, const PaStreamCallbackTimeInfo *timeInfo, - const PaStreamCallbackFlags statusFlags, void *userData); + const PaStreamCallbackFlags statusFlags, void *userData) + { + return static_cast(userData)->writeCallback(inputBuffer, outputBuffer, + framesPerBuffer, timeInfo, statusFlags); + } int writeCallback(const void *inputBuffer, void *outputBuffer, unsigned long framesPerBuffer, const PaStreamCallbackTimeInfo *timeInfo, const PaStreamCallbackFlags statusFlags); - ALCenum open(const ALCchar *name) override; + void open(const ALCchar *name) override; bool reset() override; bool start() override; void stop() override; @@ -101,14 +106,6 @@ PortPlayback::~PortPlayback() } -int PortPlayback::writeCallbackC(const void *inputBuffer, void *outputBuffer, - unsigned long framesPerBuffer, const PaStreamCallbackTimeInfo *timeInfo, - const PaStreamCallbackFlags statusFlags, void *userData) -{ - return static_cast(userData)->writeCallback(inputBuffer, outputBuffer, - framesPerBuffer, timeInfo, statusFlags); -} - int PortPlayback::writeCallback(const void*, void *outputBuffer, unsigned long framesPerBuffer, const PaStreamCallbackTimeInfo*, const PaStreamCallbackFlags) @@ -120,12 +117,12 @@ int PortPlayback::writeCallback(const void*, void *outputBuffer, } -ALCenum PortPlayback::open(const ALCchar *name) +void PortPlayback::open(const ALCchar *name) { if(!name) name = pa_device; else if(strcmp(name, pa_device) != 0) - return ALC_INVALID_VALUE; + throw al::backend_exception{ALC_INVALID_VALUE, "Device name \"%s\" not found", name}; mUpdateSize = mDevice->UpdateSize; @@ -139,25 +136,25 @@ ALCenum PortPlayback::open(const ALCchar *name) switch(mDevice->FmtType) { - case DevFmtByte: - mParams.sampleFormat = paInt8; - break; - case DevFmtUByte: - mParams.sampleFormat = paUInt8; - break; - case DevFmtUShort: - /* fall-through */ - case DevFmtShort: - mParams.sampleFormat = paInt16; - break; - case DevFmtUInt: - /* fall-through */ - case DevFmtInt: - mParams.sampleFormat = paInt32; - break; - case DevFmtFloat: - mParams.sampleFormat = paFloat32; - break; + case DevFmtByte: + mParams.sampleFormat = paInt8; + break; + case DevFmtUByte: + mParams.sampleFormat = paUInt8; + break; + case DevFmtUShort: + /* fall-through */ + case DevFmtShort: + mParams.sampleFormat = paInt16; + break; + case DevFmtUInt: + /* fall-through */ + case DevFmtInt: + mParams.sampleFormat = paInt32; + break; + case DevFmtFloat: + mParams.sampleFormat = paFloat32; + break; } retry_open: @@ -171,12 +168,11 @@ retry_open: goto retry_open; } ERR("Pa_OpenStream() returned an error: %s\n", Pa_GetErrorText(err)); - return ALC_INVALID_VALUE; + throw al::backend_exception{ALC_INVALID_VALUE, "Failed to open stream: %s", + Pa_GetErrorText(err)}; } mDevice->DeviceName = name; - return ALC_NO_ERROR; - } bool PortPlayback::reset() @@ -240,11 +236,15 @@ struct PortCapture final : public BackendBase { static int readCallbackC(const void *inputBuffer, void *outputBuffer, unsigned long framesPerBuffer, const PaStreamCallbackTimeInfo *timeInfo, - const PaStreamCallbackFlags statusFlags, void *userData); + const PaStreamCallbackFlags statusFlags, void *userData) + { + return static_cast(userData)->readCallback(inputBuffer, outputBuffer, + framesPerBuffer, timeInfo, statusFlags); + } int readCallback(const void *inputBuffer, void *outputBuffer, unsigned long framesPerBuffer, const PaStreamCallbackTimeInfo *timeInfo, const PaStreamCallbackFlags statusFlags); - ALCenum open(const ALCchar *name) override; + void open(const ALCchar *name) override; bool start() override; void stop() override; ALCenum captureSamples(al::byte *buffer, ALCuint samples) override; @@ -267,14 +267,6 @@ PortCapture::~PortCapture() } -int PortCapture::readCallbackC(const void *inputBuffer, void *outputBuffer, - unsigned long framesPerBuffer, const PaStreamCallbackTimeInfo *timeInfo, - const PaStreamCallbackFlags statusFlags, void* userData) -{ - return static_cast(userData)->readCallback(inputBuffer, outputBuffer, - framesPerBuffer, timeInfo, statusFlags); -} - int PortCapture::readCallback(const void *inputBuffer, void*, unsigned long framesPerBuffer, const PaStreamCallbackTimeInfo*, const PaStreamCallbackFlags) @@ -284,19 +276,19 @@ int PortCapture::readCallback(const void *inputBuffer, void*, } -ALCenum PortCapture::open(const ALCchar *name) +void PortCapture::open(const ALCchar *name) { if(!name) name = pa_device; else if(strcmp(name, pa_device) != 0) - return ALC_INVALID_VALUE; + throw al::backend_exception{ALC_INVALID_VALUE, "Device name \"%s\" not found", name}; ALuint samples{mDevice->BufferSize}; samples = maxu(samples, 100 * mDevice->Frequency / 1000); ALuint frame_size{mDevice->frameSizeFromFmt()}; mRing = CreateRingBuffer(samples, frame_size, false); - if(!mRing) return ALC_INVALID_VALUE; + if(!mRing) throw al::backend_exception{ALC_INVALID_VALUE, "Failed to create ring buffer"}; auto devidopt = ConfigValueInt(nullptr, "port", "capture"); if(devidopt && *devidopt >= 0) mParams.device = *devidopt; @@ -306,25 +298,26 @@ ALCenum PortCapture::open(const ALCchar *name) switch(mDevice->FmtType) { - case DevFmtByte: - mParams.sampleFormat = paInt8; - break; - case DevFmtUByte: - mParams.sampleFormat = paUInt8; - break; - case DevFmtShort: - mParams.sampleFormat = paInt16; - break; - case DevFmtInt: - mParams.sampleFormat = paInt32; - break; - case DevFmtFloat: - mParams.sampleFormat = paFloat32; - break; - case DevFmtUInt: - case DevFmtUShort: - ERR("%s samples not supported\n", DevFmtTypeString(mDevice->FmtType)); - return ALC_INVALID_VALUE; + case DevFmtByte: + mParams.sampleFormat = paInt8; + break; + case DevFmtUByte: + mParams.sampleFormat = paUInt8; + break; + case DevFmtShort: + mParams.sampleFormat = paInt16; + break; + case DevFmtInt: + mParams.sampleFormat = paInt32; + break; + case DevFmtFloat: + mParams.sampleFormat = paFloat32; + break; + case DevFmtUInt: + case DevFmtUShort: + ERR("%s samples not supported\n", DevFmtTypeString(mDevice->FmtType)); + throw al::backend_exception{ALC_INVALID_VALUE, "%s samples not supported", + DevFmtTypeString(mDevice->FmtType)}; } mParams.channelCount = static_cast(mDevice->channelsFromFmt()); @@ -333,11 +326,11 @@ ALCenum PortCapture::open(const ALCchar *name) if(err != paNoError) { ERR("Pa_OpenStream() returned an error: %s\n", Pa_GetErrorText(err)); - return ALC_INVALID_VALUE; + throw al::backend_exception{ALC_INVALID_VALUE, "Failed to open stream: %s", + Pa_GetErrorText(err)}; } mDevice->DeviceName = name; - return ALC_NO_ERROR; } diff --git a/alc/backends/pulseaudio.cpp b/alc/backends/pulseaudio.cpp index 4d3b34d9..be78ee17 100644 --- a/alc/backends/pulseaudio.cpp +++ b/alc/backends/pulseaudio.cpp @@ -663,7 +663,7 @@ struct PulsePlayback final : public BackendBase { static void streamMovedCallbackC(pa_stream *stream, void *pdata); void streamMovedCallback(pa_stream *stream); - ALCenum open(const ALCchar *name) override; + void open(const ALCchar *name) override; bool reset() override; bool start() override; void stop() override; @@ -818,7 +818,7 @@ void PulsePlayback::streamMovedCallback(pa_stream *stream) } -ALCenum PulsePlayback::open(const ALCchar *name) +void PulsePlayback::open(const ALCchar *name) { const char *pulse_name{nullptr}; const char *dev_name{nullptr}; @@ -873,8 +873,6 @@ ALCenum PulsePlayback::open(const ALCchar *name) } else mDevice->DeviceName = dev_name; - - return ALC_NO_ERROR; } bool PulsePlayback::reset() @@ -1107,7 +1105,7 @@ struct PulseCapture final : public BackendBase { static void streamMovedCallbackC(pa_stream *stream, void *pdata); void streamMovedCallback(pa_stream *stream); - ALCenum open(const ALCchar *name) override; + void open(const ALCchar *name) override; bool start() override; void stop() override; ALCenum captureSamples(al::byte *buffer, ALCuint samples) override; @@ -1192,7 +1190,7 @@ void PulseCapture::streamMovedCallback(pa_stream *stream) } -ALCenum PulseCapture::open(const ALCchar *name) +void PulseCapture::open(const ALCchar *name) { const char *pulse_name{nullptr}; if(name) @@ -1218,53 +1216,53 @@ ALCenum PulseCapture::open(const ALCchar *name) pa_channel_map chanmap{}; switch(mDevice->FmtChans) { - case DevFmtMono: - chanmap = MonoChanMap; - break; - case DevFmtStereo: - chanmap = StereoChanMap; - break; - case DevFmtQuad: - chanmap = QuadChanMap; - break; - case DevFmtX51: - chanmap = X51ChanMap; - break; - case DevFmtX51Rear: - chanmap = X51RearChanMap; - break; - case DevFmtX61: - chanmap = X61ChanMap; - break; - case DevFmtX71: - chanmap = X71ChanMap; - break; - case DevFmtAmbi3D: - throw al::backend_exception{ALC_INVALID_VALUE, "%s capture samples not supported", - DevFmtChannelsString(mDevice->FmtChans)}; + case DevFmtMono: + chanmap = MonoChanMap; + break; + case DevFmtStereo: + chanmap = StereoChanMap; + break; + case DevFmtQuad: + chanmap = QuadChanMap; + break; + case DevFmtX51: + chanmap = X51ChanMap; + break; + case DevFmtX51Rear: + chanmap = X51RearChanMap; + break; + case DevFmtX61: + chanmap = X61ChanMap; + break; + case DevFmtX71: + chanmap = X71ChanMap; + break; + case DevFmtAmbi3D: + throw al::backend_exception{ALC_INVALID_VALUE, "%s capture samples not supported", + DevFmtChannelsString(mDevice->FmtChans)}; } SetChannelOrderFromMap(mDevice, chanmap); switch(mDevice->FmtType) { - case DevFmtUByte: - mSilentVal = al::byte(0x80); - mSpec.format = PA_SAMPLE_U8; - break; - case DevFmtShort: - mSpec.format = PA_SAMPLE_S16NE; - break; - case DevFmtInt: - mSpec.format = PA_SAMPLE_S32NE; - break; - case DevFmtFloat: - mSpec.format = PA_SAMPLE_FLOAT32NE; - break; - case DevFmtByte: - case DevFmtUShort: - case DevFmtUInt: - throw al::backend_exception{ALC_INVALID_VALUE, "%s capture samples not supported", - DevFmtTypeString(mDevice->FmtType)}; + case DevFmtUByte: + mSilentVal = al::byte(0x80); + mSpec.format = PA_SAMPLE_U8; + break; + case DevFmtShort: + mSpec.format = PA_SAMPLE_S16NE; + break; + case DevFmtInt: + mSpec.format = PA_SAMPLE_S32NE; + break; + case DevFmtFloat: + mSpec.format = PA_SAMPLE_FLOAT32NE; + break; + case DevFmtByte: + case DevFmtUShort: + case DevFmtUInt: + throw al::backend_exception{ALC_INVALID_VALUE, "%s capture samples not supported", + DevFmtTypeString(mDevice->FmtType)}; } mSpec.rate = mDevice->Frequency; mSpec.channels = static_cast(mDevice->channelsFromFmt()); @@ -1297,8 +1295,6 @@ ALCenum PulseCapture::open(const ALCchar *name) &PulseCapture::sourceNameCallbackC, this)}; wait_for_operation(op, plock); } - - return ALC_NO_ERROR; } bool PulseCapture::start() diff --git a/alc/backends/qsa.cpp b/alc/backends/qsa.cpp index 5fee2989..872a8541 100644 --- a/alc/backends/qsa.cpp +++ b/alc/backends/qsa.cpp @@ -34,6 +34,7 @@ #include #include "alcmain.h" +#include "alexcpt.h" #include "alu.h" #include "threads.h" @@ -174,7 +175,7 @@ struct PlaybackWrapper final : public BackendBase { PlaybackWrapper(ALCdevice *device) noexcept : BackendBase{device} { } ~PlaybackWrapper() override; - ALCenum open(const ALCchar *name) override; + void open(const ALCchar *name) override; bool reset() override; bool start() override; void stop() override; @@ -613,11 +614,18 @@ PlaybackWrapper::~PlaybackWrapper() qsa_close_playback(this); } -ALCenum PlaybackWrapper::open(const ALCchar *name) -{ return qsa_open_playback(this, name); } +void PlaybackWrapper::open(const ALCchar *name) +{ + if(auto err = qsa_open_playback(this, name)) + throw al::backend_exception{ALC_INVALID_VALUE, "%d", err}; +} bool PlaybackWrapper::reset() -{ return qsa_reset_playback(this); } +{ + if(!qsa_reset_playback(this)) + throw al::backend_exception{ALC_INVALID_VALUE, ""}; + return true; +} bool PlaybackWrapper::start() { return qsa_start_playback(this); } @@ -634,7 +642,7 @@ struct CaptureWrapper final : public BackendBase { CaptureWrapper(ALCdevice *device) noexcept : BackendBase{device} { } ~CaptureWrapper() override; - ALCenum open(const ALCchar *name) override; + void open(const ALCchar *name) override; bool start() override; void stop() override; ALCenum captureSamples(al::byte *buffer, ALCuint samples) override; @@ -891,8 +899,11 @@ CaptureWrapper::~CaptureWrapper() qsa_close_capture(this); } -ALCenum CaptureWrapper::open(const ALCchar *name) -{ return qsa_open_capture(this, name); } +void CaptureWrapper::open(const ALCchar *name) +{ + if(auto err = qsa_open_capture(this, name)) + throw al::backend_exception{ALC_INVALID_VALUE, "%d", err}; +} bool CaptureWrapper::start() { qsa_start_capture(this); return true; } diff --git a/alc/backends/sdl2.cpp b/alc/backends/sdl2.cpp index 71616906..1063ca7a 100644 --- a/alc/backends/sdl2.cpp +++ b/alc/backends/sdl2.cpp @@ -30,6 +30,7 @@ #include "AL/al.h" #include "alcmain.h" +#include "alexcpt.h" #include "almalloc.h" #include "alu.h" #include "logging.h" @@ -54,7 +55,7 @@ struct Sdl2Backend final : public BackendBase { static void audioCallbackC(void *ptr, Uint8 *stream, int len); void audioCallback(Uint8 *stream, int len); - ALCenum open(const ALCchar *name) override; + void open(const ALCchar *name) override; bool reset() override; bool start() override; void stop() override; @@ -89,20 +90,20 @@ void Sdl2Backend::audioCallback(Uint8 *stream, int len) aluMixData(mDevice, stream, ulen / mFrameSize); } -ALCenum Sdl2Backend::open(const ALCchar *name) +void Sdl2Backend::open(const ALCchar *name) { SDL_AudioSpec want{}, have{}; want.freq = static_cast(mDevice->Frequency); switch(mDevice->FmtType) { - case DevFmtUByte: want.format = AUDIO_U8; break; - case DevFmtByte: want.format = AUDIO_S8; break; - case DevFmtUShort: want.format = AUDIO_U16SYS; break; - case DevFmtShort: want.format = AUDIO_S16SYS; break; - case DevFmtUInt: /* fall-through */ - case DevFmtInt: want.format = AUDIO_S32SYS; break; - case DevFmtFloat: want.format = AUDIO_F32; break; + case DevFmtUByte: want.format = AUDIO_U8; break; + case DevFmtByte: want.format = AUDIO_S8; break; + case DevFmtUShort: want.format = AUDIO_U16SYS; break; + case DevFmtShort: want.format = AUDIO_S16SYS; break; + case DevFmtUInt: /* fall-through */ + case DevFmtInt: want.format = AUDIO_S32SYS; break; + case DevFmtFloat: want.format = AUDIO_F32; break; } want.channels = (mDevice->FmtChans == DevFmtMono) ? 1 : 2; want.samples = static_cast(mDevice->UpdateSize); @@ -114,19 +115,19 @@ ALCenum Sdl2Backend::open(const ALCchar *name) */ if(!name || strcmp(name, defaultDeviceName) == 0) mDeviceID = SDL_OpenAudioDevice(nullptr, SDL_FALSE, &want, &have, - SDL_AUDIO_ALLOW_ANY_CHANGE); + SDL_AUDIO_ALLOW_ANY_CHANGE); else { const size_t prefix_len = strlen(DEVNAME_PREFIX); if(strncmp(name, DEVNAME_PREFIX, prefix_len) == 0) mDeviceID = SDL_OpenAudioDevice(name+prefix_len, SDL_FALSE, &want, &have, - SDL_AUDIO_ALLOW_ANY_CHANGE); + SDL_AUDIO_ALLOW_ANY_CHANGE); else mDeviceID = SDL_OpenAudioDevice(name, SDL_FALSE, &want, &have, - SDL_AUDIO_ALLOW_ANY_CHANGE); + SDL_AUDIO_ALLOW_ANY_CHANGE); } if(mDeviceID == 0) - return ALC_INVALID_VALUE; + throw al::backend_exception{ALC_INVALID_VALUE, "%s", SDL_GetError()}; mDevice->Frequency = static_cast(have.freq); if(have.channels == 1) @@ -136,19 +137,21 @@ ALCenum Sdl2Backend::open(const ALCchar *name) else { ERR("Got unhandled SDL channel count: %d\n", int{have.channels}); - return ALC_INVALID_VALUE; + throw al::backend_exception{ALC_INVALID_VALUE, "Unhandled SDL channel count: %d", + int{have.channels}}; } switch(have.format) { - case AUDIO_U8: mDevice->FmtType = DevFmtUByte; break; - case AUDIO_S8: mDevice->FmtType = DevFmtByte; break; - case AUDIO_U16SYS: mDevice->FmtType = DevFmtUShort; break; - case AUDIO_S16SYS: mDevice->FmtType = DevFmtShort; break; - case AUDIO_S32SYS: mDevice->FmtType = DevFmtInt; break; - case AUDIO_F32SYS: mDevice->FmtType = DevFmtFloat; break; - default: - ERR("Got unsupported SDL format: 0x%04x\n", have.format); - return ALC_INVALID_VALUE; + case AUDIO_U8: mDevice->FmtType = DevFmtUByte; break; + case AUDIO_S8: mDevice->FmtType = DevFmtByte; break; + case AUDIO_U16SYS: mDevice->FmtType = DevFmtUShort; break; + case AUDIO_S16SYS: mDevice->FmtType = DevFmtShort; break; + case AUDIO_S32SYS: mDevice->FmtType = DevFmtInt; break; + case AUDIO_F32SYS: mDevice->FmtType = DevFmtFloat; break; + default: + ERR("Got unsupported SDL format: 0x%04x\n", have.format); + throw al::backend_exception{ALC_INVALID_VALUE, "Unhandled SDL format: 0x%04x", + have.format}; } mDevice->UpdateSize = have.samples; mDevice->BufferSize = have.samples * 2; /* SDL always (tries to) use two periods. */ @@ -160,7 +163,6 @@ ALCenum Sdl2Backend::open(const ALCchar *name) mUpdateSize = mDevice->UpdateSize; mDevice->DeviceName = name ? name : defaultDeviceName; - return ALC_NO_ERROR; } bool Sdl2Backend::reset() diff --git a/alc/backends/sndio.cpp b/alc/backends/sndio.cpp index d2654853..e0c70762 100644 --- a/alc/backends/sndio.cpp +++ b/alc/backends/sndio.cpp @@ -30,6 +30,7 @@ #include #include "alcmain.h" +#include "alexcpt.h" #include "alu.h" #include "threads.h" #include "vector.h" @@ -49,7 +50,7 @@ struct SndioPlayback final : public BackendBase { int mixerProc(); - ALCenum open(const ALCchar *name) override; + void open(const ALCchar *name) override; bool reset() override; bool start() override; void stop() override; @@ -106,22 +107,21 @@ int SndioPlayback::mixerProc() } -ALCenum SndioPlayback::open(const ALCchar *name) +void SndioPlayback::open(const ALCchar *name) { if(!name) name = sndio_device; else if(strcmp(name, sndio_device) != 0) - return ALC_INVALID_VALUE; + throw al::backend_exception{ALC_INVALID_VALUE, "Device name \"%s\" not found", name}; mSndHandle = sio_open(nullptr, SIO_PLAY, 0); if(mSndHandle == nullptr) { ERR("Could not open device\n"); - return ALC_INVALID_VALUE; + throw al::backend_exception{ALC_INVALID_VALUE, "Could not open sound device"}; } mDevice->DeviceName = name; - return ALC_NO_ERROR; } bool SndioPlayback::reset() @@ -249,7 +249,7 @@ struct SndioCapture final : public BackendBase { int recordProc(); - ALCenum open(const ALCchar *name) override; + void open(const ALCchar *name) override; bool start() override; void stop() override; ALCenum captureSamples(al::byte *buffer, ALCuint samples) override; @@ -319,18 +319,18 @@ int SndioCapture::recordProc() } -ALCenum SndioCapture::open(const ALCchar *name) +void SndioCapture::open(const ALCchar *name) { if(!name) name = sndio_device; else if(strcmp(name, sndio_device) != 0) - return ALC_INVALID_VALUE; + throw al::backend_exception{ALC_INVALID_VALUE, "Device name \"%s\" not found", name}; mSndHandle = sio_open(nullptr, SIO_REC, 0); if(mSndHandle == nullptr) { ERR("Could not open device\n"); - return ALC_INVALID_VALUE; + throw al::backend_exception{ALC_INVALID_VALUE, "Could not open sound device"}; } sio_par par; @@ -338,33 +338,34 @@ ALCenum SndioCapture::open(const ALCchar *name) switch(mDevice->FmtType) { - case DevFmtByte: - par.bps = 1; - par.sig = 1; - break; - case DevFmtUByte: - par.bps = 1; - par.sig = 0; - break; - case DevFmtShort: - par.bps = 2; - par.sig = 1; - break; - case DevFmtUShort: - par.bps = 2; - par.sig = 0; - break; - case DevFmtInt: - par.bps = 4; - par.sig = 1; - break; - case DevFmtUInt: - par.bps = 4; - par.sig = 0; - break; - case DevFmtFloat: - ERR("%s capture samples not supported\n", DevFmtTypeString(mDevice->FmtType)); - return ALC_INVALID_VALUE; + case DevFmtByte: + par.bps = 1; + par.sig = 1; + break; + case DevFmtUByte: + par.bps = 1; + par.sig = 0; + break; + case DevFmtShort: + par.bps = 2; + par.sig = 1; + break; + case DevFmtUShort: + par.bps = 2; + par.sig = 0; + break; + case DevFmtInt: + par.bps = 4; + par.sig = 1; + break; + case DevFmtUInt: + par.bps = 4; + par.sig = 0; + break; + case DevFmtFloat: + ERR("%s capture samples not supported\n", DevFmtTypeString(mDevice->FmtType)); + throw al::backend_exception{ALC_INVALID_VALUE, "%s capture samples not supported", + DevFmtTypeString(mDevice->FmtType)}; } par.bits = par.bps * 8; par.le = SIO_LE_NATIVE; @@ -381,13 +382,14 @@ ALCenum SndioCapture::open(const ALCchar *name) if(!sio_setpar(mSndHandle, &par) || !sio_getpar(mSndHandle, &par)) { ERR("Failed to set device parameters\n"); - return ALC_INVALID_VALUE; + throw al::backend_exception{ALC_INVALID_VALUE, "Failed to set device praameters"}; } if(par.bits != par.bps*8) { ERR("Padded samples not supported (%u of %u bits)\n", par.bits, par.bps*8); - return ALC_INVALID_VALUE; + throw al::backend_exception{ALC_INVALID_VALUE, + "Padded samples not supported (got %u of %u bits)", par.bits, par.bps*8}; } if(!((mDevice->FmtType == DevFmtByte && par.bits == 8 && par.sig != 0) || @@ -401,20 +403,21 @@ ALCenum SndioCapture::open(const ALCchar *name) ERR("Failed to set format %s %s %uhz, got %c%u %u-channel %uhz instead\n", DevFmtTypeString(mDevice->FmtType), DevFmtChannelsString(mDevice->FmtChans), mDevice->Frequency, par.sig?'s':'u', par.bits, par.rchan, par.rate); - return ALC_INVALID_VALUE; + throw al::backend_exception{ALC_INVALID_VALUE, "Could not set format %s %s %uhz", + DevFmtTypeString(mDevice->FmtType), DevFmtChannelsString(mDevice->FmtChans), + mDevice->Frequency}; } mRing = CreateRingBuffer(mDevice->BufferSize, par.bps*par.rchan, false); if(!mRing) { ERR("Failed to allocate %u-byte ringbuffer\n", mDevice->BufferSize*par.bps*par.rchan); - return ALC_OUT_OF_MEMORY; + throw al::backend_exception{ALC_OUT_OF_MEMORY, "Failed to allocate ring buffer"}; } SetDefaultChannelOrder(mDevice); mDevice->DeviceName = name; - return ALC_NO_ERROR; } bool SndioCapture::start() diff --git a/alc/backends/solaris.cpp b/alc/backends/solaris.cpp index 128924bb..5963a4b2 100644 --- a/alc/backends/solaris.cpp +++ b/alc/backends/solaris.cpp @@ -39,6 +39,7 @@ #include #include "alcmain.h" +#include "alexcpt.h" #include "alu.h" #include "alconfig.h" #include "threads.h" @@ -61,7 +62,7 @@ struct SolarisBackend final : public BackendBase { int mixerProc(); - ALCenum open(const ALCchar *name) override; + void open(const ALCchar *name) override; bool reset() override; bool start() override; void stop() override; @@ -142,22 +143,22 @@ int SolarisBackend::mixerProc() } -ALCenum SolarisBackend::open(const ALCchar *name) +void SolarisBackend::open(const ALCchar *name) { if(!name) name = solaris_device; else if(strcmp(name, solaris_device) != 0) - return ALC_INVALID_VALUE; + throw al::backend_exception{ALC_INVALID_VALUE, "Device name \"%s\" not found", name}; mFd = ::open(solaris_driver.c_str(), O_WRONLY); if(mFd == -1) { ERR("Could not open %s: %s\n", solaris_driver.c_str(), strerror(errno)); - return ALC_INVALID_VALUE; + throw al::backend_exception{ALC_INVALID_VALUE, "Could not open %s: %s", + solaris_driver.c_str(), strerror(errno)}; } mDevice->DeviceName = name; - return ALC_NO_ERROR; } bool SolarisBackend::reset() diff --git a/alc/backends/wasapi.cpp b/alc/backends/wasapi.cpp index 2a610c8d..b6f5b5fb 100644 --- a/alc/backends/wasapi.cpp +++ b/alc/backends/wasapi.cpp @@ -55,6 +55,7 @@ #include #include "alcmain.h" +#include "alexcpt.h" #include "alu.h" #include "ringbuffer.h" #include "compat.h" @@ -610,7 +611,7 @@ struct WasapiPlayback final : public BackendBase, WasapiProxy { int mixerProc(); - ALCenum open(const ALCchar *name) override; + void open(const ALCchar *name) override; HRESULT openProxy() override; void closeProxy() override; @@ -708,7 +709,7 @@ FORCE_ALIGN int WasapiPlayback::mixerProc() } -ALCenum WasapiPlayback::open(const ALCchar *name) +void WasapiPlayback::open(const ALCchar *name) { HRESULT hr{S_OK}; @@ -762,10 +763,8 @@ ALCenum WasapiPlayback::open(const ALCchar *name) mDevId.clear(); ERR("Device init failed: 0x%08lx\n", hr); - return ALC_INVALID_VALUE; + throw al::backend_exception{ALC_INVALID_VALUE, "Device init failed: 0x%08lx", hr}; } - - return ALC_NO_ERROR; } HRESULT WasapiPlayback::openProxy() @@ -815,7 +814,9 @@ void WasapiPlayback::closeProxy() bool WasapiPlayback::reset() { HRESULT hr{pushMessage(MsgType::ResetDevice).get()}; - return SUCCEEDED(hr) ? true : false; + if(FAILED(hr)) + throw al::backend_exception{ALC_INVALID_VALUE, "0x%08lx", hr}; + return true; } HRESULT WasapiPlayback::resetProxy() @@ -1151,7 +1152,7 @@ struct WasapiCapture final : public BackendBase, WasapiProxy { int recordProc(); - ALCenum open(const ALCchar *name) override; + void open(const ALCchar *name) override; HRESULT openProxy() override; void closeProxy() override; @@ -1283,7 +1284,7 @@ FORCE_ALIGN int WasapiCapture::recordProc() } -ALCenum WasapiCapture::open(const ALCchar *name) +void WasapiCapture::open(const ALCchar *name) { HRESULT hr{S_OK}; @@ -1337,18 +1338,16 @@ ALCenum WasapiCapture::open(const ALCchar *name) mDevId.clear(); ERR("Device init failed: 0x%08lx\n", hr); - return ALC_INVALID_VALUE; + throw al::backend_exception{ALC_INVALID_VALUE, "Device init failed: 0x%08lx", hr}; } hr = pushMessage(MsgType::ResetDevice).get(); if(FAILED(hr)) { if(hr == E_OUTOFMEMORY) - return ALC_OUT_OF_MEMORY; - return ALC_INVALID_VALUE; + throw al::backend_exception{ALC_OUT_OF_MEMORY, "Out of memory"}; + throw al::backend_exception{ALC_INVALID_VALUE, "Device reset failed"}; } - - return ALC_NO_ERROR; } HRESULT WasapiCapture::openProxy() diff --git a/alc/backends/wave.cpp b/alc/backends/wave.cpp index 797a9fa5..927cb276 100644 --- a/alc/backends/wave.cpp +++ b/alc/backends/wave.cpp @@ -38,6 +38,7 @@ #include "albyte.h" #include "alcmain.h" #include "alconfig.h" +#include "alexcpt.h" #include "almalloc.h" #include "alnumeric.h" #include "alu.h" @@ -96,7 +97,7 @@ struct WaveBackend final : public BackendBase { int mixerProc(); - ALCenum open(const ALCchar *name) override; + void open(const ALCchar *name) override; bool reset() override; bool start() override; void stop() override; @@ -202,15 +203,15 @@ int WaveBackend::mixerProc() return 0; } -ALCenum WaveBackend::open(const ALCchar *name) +void WaveBackend::open(const ALCchar *name) { const char *fname{GetConfigValue(nullptr, "wave", "file", "")}; - if(!fname[0]) return ALC_INVALID_VALUE; + if(!fname[0]) throw al::backend_exception{ALC_INVALID_VALUE, "No wave output filename"}; if(!name) name = waveDevice; else if(strcmp(name, waveDevice) != 0) - return ALC_INVALID_VALUE; + throw al::backend_exception{ALC_INVALID_VALUE, "Device name \"%s\" not found", name}; #ifdef _WIN32 { @@ -223,12 +224,11 @@ ALCenum WaveBackend::open(const ALCchar *name) if(!mFile) { ERR("Could not open file '%s': %s\n", fname, strerror(errno)); - return ALC_INVALID_VALUE; + throw al::backend_exception{ALC_INVALID_VALUE, "Could not open file '%s': %s", fname, + strerror(errno)}; } mDevice->DeviceName = name; - - return ALC_NO_ERROR; } bool WaveBackend::reset() diff --git a/alc/backends/winmm.cpp b/alc/backends/winmm.cpp index d58fa959..c287e136 100644 --- a/alc/backends/winmm.cpp +++ b/alc/backends/winmm.cpp @@ -38,6 +38,7 @@ #include #include "alcmain.h" +#include "alexcpt.h" #include "alu.h" #include "ringbuffer.h" #include "strutils.h" @@ -131,7 +132,7 @@ struct WinMMPlayback final : public BackendBase { int mixerProc(); - ALCenum open(const ALCchar *name) override; + void open(const ALCchar *name) override; bool reset() override; bool start() override; void stop() override; @@ -212,7 +213,7 @@ FORCE_ALIGN int WinMMPlayback::mixerProc() } -ALCenum WinMMPlayback::open(const ALCchar *name) +void WinMMPlayback::open(const ALCchar *name) { if(PlaybackDevices.empty()) ProbePlaybackDevices(); @@ -221,7 +222,8 @@ ALCenum WinMMPlayback::open(const ALCchar *name) auto iter = name ? std::find(PlaybackDevices.cbegin(), PlaybackDevices.cend(), name) : PlaybackDevices.cbegin(); - if(iter == PlaybackDevices.cend()) return ALC_INVALID_VALUE; + if(iter == PlaybackDevices.cend()) + throw al::backend_exception{ALC_INVALID_VALUE, "Device name \"%s\" not found", name}; auto DeviceID = static_cast(std::distance(PlaybackDevices.cbegin(), iter)); retry_open: @@ -256,11 +258,10 @@ retry_open: goto retry_open; } ERR("waveOutOpen failed: %u\n", res); - return ALC_INVALID_VALUE; + throw al::backend_exception{ALC_INVALID_VALUE, "waveOutOpen failed: %u", res}; } mDevice->DeviceName = PlaybackDevices[DeviceID]; - return ALC_NO_ERROR; } bool WinMMPlayback::reset() @@ -373,7 +374,7 @@ struct WinMMCapture final : public BackendBase { int captureProc(); - ALCenum open(const ALCchar *name) override; + void open(const ALCchar *name) override; bool start() override; void stop() override; ALCenum captureSamples(al::byte *buffer, ALCuint samples) override; @@ -456,7 +457,7 @@ int WinMMCapture::captureProc() } -ALCenum WinMMCapture::open(const ALCchar *name) +void WinMMCapture::open(const ALCchar *name) { if(CaptureDevices.empty()) ProbeCaptureDevices(); @@ -465,36 +466,39 @@ ALCenum WinMMCapture::open(const ALCchar *name) auto iter = name ? std::find(CaptureDevices.cbegin(), CaptureDevices.cend(), name) : CaptureDevices.cbegin(); - if(iter == CaptureDevices.cend()) return ALC_INVALID_VALUE; + if(iter == CaptureDevices.cend()) + throw al::backend_exception{ALC_INVALID_VALUE, "Device name \"%s\" not found", name}; auto DeviceID = static_cast(std::distance(CaptureDevices.cbegin(), iter)); switch(mDevice->FmtChans) { - case DevFmtMono: - case DevFmtStereo: - break; - - case DevFmtQuad: - case DevFmtX51: - case DevFmtX51Rear: - case DevFmtX61: - case DevFmtX71: - case DevFmtAmbi3D: - return ALC_INVALID_ENUM; + case DevFmtMono: + case DevFmtStereo: + break; + + case DevFmtQuad: + case DevFmtX51: + case DevFmtX51Rear: + case DevFmtX61: + case DevFmtX71: + case DevFmtAmbi3D: + throw al::backend_exception{ALC_INVALID_VALUE, "%s capture not supported", + DevFmtChannelsString(mDevice->FmtChans)}; } switch(mDevice->FmtType) { - case DevFmtUByte: - case DevFmtShort: - case DevFmtInt: - case DevFmtFloat: - break; - - case DevFmtByte: - case DevFmtUShort: - case DevFmtUInt: - return ALC_INVALID_ENUM; + case DevFmtUByte: + case DevFmtShort: + case DevFmtInt: + case DevFmtFloat: + break; + + case DevFmtByte: + case DevFmtUShort: + case DevFmtUInt: + throw al::backend_exception{ALC_INVALID_VALUE, "%s samples not supported", + DevFmtTypeString(mDevice->FmtType)}; } mFormat = WAVEFORMATEX{}; @@ -513,7 +517,7 @@ ALCenum WinMMCapture::open(const ALCchar *name) if(res != MMSYSERR_NOERROR) { ERR("waveInOpen failed: %u\n", res); - return ALC_INVALID_VALUE; + throw al::backend_exception{ALC_INVALID_VALUE, "waveInOpen failed: %u", res}; } // Ensure each buffer is 50ms each @@ -526,7 +530,7 @@ ALCenum WinMMCapture::open(const ALCchar *name) CapturedDataSize = static_cast(maxz(CapturedDataSize, BufferSize*mWaveBuffer.size())); mRing = CreateRingBuffer(CapturedDataSize, mFormat.nBlockAlign, false); - if(!mRing) return ALC_INVALID_VALUE; + if(!mRing) throw al::backend_exception{ALC_INVALID_VALUE, "Could not create ring buffer"}; al_free(mWaveBuffer[0].lpData); mWaveBuffer[0] = WAVEHDR{}; @@ -540,7 +544,6 @@ ALCenum WinMMCapture::open(const ALCchar *name) } mDevice->DeviceName = CaptureDevices[DeviceID]; - return ALC_NO_ERROR; } bool WinMMCapture::start() -- cgit v1.2.3 From 52a003e9bb7c870f26436b38e62edc96385805dc Mon Sep 17 00:00:00 2001 From: Chris Robinson Date: Mon, 7 Oct 2019 23:22:06 -0700 Subject: Avoid raw lock/unlock calls --- alc/backends/alsa.cpp | 12 ++++-------- alc/backends/coreaudio.cpp | 3 +-- alc/backends/dsound.cpp | 5 +++-- alc/backends/jack.cpp | 10 ++++------ alc/backends/null.cpp | 3 +-- alc/backends/opensl.cpp | 10 ++++------ alc/backends/oss.cpp | 7 +++---- alc/backends/portaudio.cpp | 3 +-- alc/backends/qsa.cpp | 7 +++---- alc/backends/sndio.cpp | 7 ++++--- alc/backends/solaris.cpp | 7 +++---- alc/backends/wasapi.cpp | 7 +++---- alc/backends/wave.cpp | 7 ++++--- alc/backends/winmm.cpp | 14 ++++++-------- 14 files changed, 44 insertions(+), 58 deletions(-) (limited to 'alc/backends/alsa.cpp') diff --git a/alc/backends/alsa.cpp b/alc/backends/alsa.cpp index 2e157602..a9eb6d5f 100644 --- a/alc/backends/alsa.cpp +++ b/alc/backends/alsa.cpp @@ -471,7 +471,7 @@ int AlsaPlayback::mixerProc() avail -= avail%update_size; // it is possible that contiguous areas are smaller, thus we use a loop - lock(); + std::lock_guard _{*this}; while(avail > 0) { snd_pcm_uframes_t frames{avail}; @@ -498,7 +498,6 @@ int AlsaPlayback::mixerProc() avail -= frames; } - unlock(); } return 0; @@ -551,7 +550,7 @@ int AlsaPlayback::mixerNoMMapProc() continue; } - lock(); + std::lock_guard _{*this}; al::byte *WritePtr{mBuffer.data()}; avail = snd_pcm_bytes_to_frames(mPcmHandle, static_cast(mBuffer.size())); aluMixData(mDevice, WritePtr, static_cast(avail)); @@ -586,7 +585,6 @@ int AlsaPlayback::mixerNoMMapProc() if(ret < 0) break; } } - unlock(); } return 0; @@ -847,7 +845,7 @@ ClockLatency AlsaPlayback::getClockLatency() { ClockLatency ret; - lock(); + std::lock_guard _{*this}; ret.ClockTime = GetDeviceClockTime(mDevice); snd_pcm_sframes_t delay{}; int err{snd_pcm_delay(mPcmHandle, &delay)}; @@ -858,7 +856,6 @@ ClockLatency AlsaPlayback::getClockLatency() } ret.Latency = std::chrono::seconds{std::max(0, delay)}; ret.Latency /= mDevice->Frequency; - unlock(); return ret; } @@ -1188,7 +1185,7 @@ ClockLatency AlsaCapture::getClockLatency() { ClockLatency ret; - lock(); + std::lock_guard _{*this}; ret.ClockTime = GetDeviceClockTime(mDevice); snd_pcm_sframes_t delay{}; int err{snd_pcm_delay(mPcmHandle, &delay)}; @@ -1199,7 +1196,6 @@ ClockLatency AlsaCapture::getClockLatency() } ret.Latency = std::chrono::seconds{std::max(0, delay)}; ret.Latency /= mDevice->Frequency; - unlock(); return ret; } diff --git a/alc/backends/coreaudio.cpp b/alc/backends/coreaudio.cpp index 9254dbe0..3a97c105 100644 --- a/alc/backends/coreaudio.cpp +++ b/alc/backends/coreaudio.cpp @@ -81,9 +81,8 @@ CoreAudioPlayback::~CoreAudioPlayback() OSStatus CoreAudioPlayback::MixerProc(AudioUnitRenderActionFlags*, const AudioTimeStamp*, UInt32, UInt32, AudioBufferList *ioData) { - lock(); + std::lock_guard _{*this}; aluMixData(mDevice, ioData->mBuffers[0].mData, ioData->mBuffers[0].mDataByteSize/mFrameSize); - unlock(); return noErr; } diff --git a/alc/backends/dsound.cpp b/alc/backends/dsound.cpp index 19a3c604..d48b74e2 100644 --- a/alc/backends/dsound.cpp +++ b/alc/backends/dsound.cpp @@ -276,17 +276,18 @@ FORCE_ALIGN int DSoundPlayback::mixerProc() if(SUCCEEDED(err)) { - lock(); + std::unique_lock dlock{*this}; aluMixData(mDevice, WritePtr1, WriteCnt1/FrameSize); if(WriteCnt2 > 0) aluMixData(mDevice, WritePtr2, WriteCnt2/FrameSize); - unlock(); + dlock.unlock(); mBuffer->Unlock(WritePtr1, WriteCnt1, WritePtr2, WriteCnt2); } else { ERR("Buffer lock error: %#lx\n", err); + std::lock_guard _{*this}; aluHandleDisconnect(mDevice, "Failed to lock output buffer: 0x%lx", err); return 1; } diff --git a/alc/backends/jack.cpp b/alc/backends/jack.cpp index c7e2839c..7c3f1822 100644 --- a/alc/backends/jack.cpp +++ b/alc/backends/jack.cpp @@ -296,15 +296,15 @@ int JackPlayback::mixerProc() SetRTPriority(); althrd_setname(MIXER_THREAD_NAME); - lock(); + std::unique_lock dlock{*this}; while(!mKillNow.load(std::memory_order_acquire) && mDevice->Connected.load(std::memory_order_acquire)) { if(mRing->writeSpace() < mDevice->UpdateSize) { - unlock(); + dlock.unlock(); mSem.wait(); - lock(); + dlock.lock(); continue; } @@ -320,7 +320,6 @@ int JackPlayback::mixerProc() aluMixData(mDevice, data.second.buf, len2); mRing->writeAdvance(todo); } - unlock(); return 0; } @@ -484,11 +483,10 @@ ClockLatency JackPlayback::getClockLatency() { ClockLatency ret; - lock(); + std::lock_guard _{*this}; ret.ClockTime = GetDeviceClockTime(mDevice); ret.Latency = std::chrono::seconds{mRing->readSpace()}; ret.Latency /= mDevice->Frequency; - unlock(); return ret; } diff --git a/alc/backends/null.cpp b/alc/backends/null.cpp index aca59605..bc2a0c9c 100644 --- a/alc/backends/null.cpp +++ b/alc/backends/null.cpp @@ -86,9 +86,8 @@ int NullBackend::mixerProc() } while(avail-done >= mDevice->UpdateSize) { - lock(); + std::lock_guard _{*this}; aluMixData(mDevice, nullptr, mDevice->UpdateSize); - unlock(); done += mDevice->UpdateSize; } diff --git a/alc/backends/opensl.cpp b/alc/backends/opensl.cpp index 4e4ceb5b..f546f168 100644 --- a/alc/backends/opensl.cpp +++ b/alc/backends/opensl.cpp @@ -228,7 +228,7 @@ int OpenSLPlayback::mixerProc() PRINTERR(result, "bufferQueue->GetInterface SL_IID_PLAY"); } - lock(); + std::unique_lock dlock{*this}; if(SL_RESULT_SUCCESS != result) aluHandleDisconnect(mDevice, "Failed to get playback buffer: 0x%08x", result); @@ -254,9 +254,9 @@ int OpenSLPlayback::mixerProc() if(mRing->writeSpace() == 0) { - unlock(); + dlock.unlock(); mSem.wait(); - lock(); + dlock.lock(); continue; } } @@ -292,7 +292,6 @@ int OpenSLPlayback::mixerProc() data.first.buf += mDevice->UpdateSize*mFrameSize; } } - unlock(); return 0; } @@ -617,11 +616,10 @@ ClockLatency OpenSLPlayback::getClockLatency() { ClockLatency ret; - lock(); + std::lock_guard _{*this}; ret.ClockTime = GetDeviceClockTime(mDevice); ret.Latency = std::chrono::seconds{mRing->readSpace() * mDevice->UpdateSize}; ret.Latency /= mDevice->Frequency; - unlock(); return ret; } diff --git a/alc/backends/oss.cpp b/alc/backends/oss.cpp index 1e3ad28b..5ab07dbe 100644 --- a/alc/backends/oss.cpp +++ b/alc/backends/oss.cpp @@ -279,7 +279,7 @@ int OSSPlayback::mixerProc() const ALuint frame_size{mDevice->frameSizeFromFmt()}; - lock(); + std::unique_lock dlock{*this}; while(!mKillNow.load(std::memory_order_acquire) && mDevice->Connected.load(std::memory_order_acquire)) { @@ -287,9 +287,9 @@ int OSSPlayback::mixerProc() pollitem.fd = mFd; pollitem.events = POLLOUT; - unlock(); + dlock.unlock(); int pret{poll(&pollitem, 1, 1000)}; - lock(); + dlock.lock(); if(pret < 0) { if(errno == EINTR || errno == EAGAIN) @@ -324,7 +324,6 @@ int OSSPlayback::mixerProc() write_ptr += wrote; } } - unlock(); return 0; } diff --git a/alc/backends/portaudio.cpp b/alc/backends/portaudio.cpp index 7847f41d..ba8e4984 100644 --- a/alc/backends/portaudio.cpp +++ b/alc/backends/portaudio.cpp @@ -110,9 +110,8 @@ int PortPlayback::writeCallback(const void*, void *outputBuffer, unsigned long framesPerBuffer, const PaStreamCallbackTimeInfo*, const PaStreamCallbackFlags) { - lock(); + std::lock_guard _{*this}; aluMixData(mDevice, outputBuffer, static_cast(framesPerBuffer)); - unlock(); return 0; } diff --git a/alc/backends/qsa.cpp b/alc/backends/qsa.cpp index 872a8541..5ed65798 100644 --- a/alc/backends/qsa.cpp +++ b/alc/backends/qsa.cpp @@ -207,7 +207,7 @@ FORCE_ALIGN static int qsa_proc_playback(void *ptr) const ALint frame_size = device->frameSizeFromFmt(); - self->lock(); + std::unique_lock dlock{*self}; while(!data->mKillNow.load(std::memory_order_acquire)) { pollfd pollitem{}; @@ -215,9 +215,9 @@ FORCE_ALIGN static int qsa_proc_playback(void *ptr) pollitem.events = POLLOUT; /* Select also works like time slice to OS */ - self->unlock(); + dlock.unlock(); sret = poll(&pollitem, 1, 2000); - self->lock(); + dlock.lock(); if(sret == -1) { if(errno == EINTR || errno == EAGAIN) @@ -266,7 +266,6 @@ FORCE_ALIGN static int qsa_proc_playback(void *ptr) } } } - self->unlock(); return 0; } diff --git a/alc/backends/sndio.cpp b/alc/backends/sndio.cpp index e0c70762..5657a241 100644 --- a/alc/backends/sndio.cpp +++ b/alc/backends/sndio.cpp @@ -85,9 +85,10 @@ int SndioPlayback::mixerProc() ALubyte *WritePtr{mBuffer.data()}; size_t len{mBuffer.size()}; - lock(); - aluMixData(mDevice, WritePtr, static_cast(len/frameSize)); - unlock(); + { + std::lock_guard _{*this}; + aluMixData(mDevice, WritePtr, static_cast(len/frameSize)); + } while(len > 0 && !mKillNow.load(std::memory_order_acquire)) { size_t wrote{sio_write(mSndHandle, WritePtr, len)}; diff --git a/alc/backends/solaris.cpp b/alc/backends/solaris.cpp index 5963a4b2..79cc224d 100644 --- a/alc/backends/solaris.cpp +++ b/alc/backends/solaris.cpp @@ -91,7 +91,7 @@ int SolarisBackend::mixerProc() const ALuint frame_size{mDevice->frameSizeFromFmt()}; - lock(); + std::unique_lock dlock{*this}; while(!mKillNow.load(std::memory_order_acquire) && mDevice->Connected.load(std::memory_order_acquire)) { @@ -99,9 +99,9 @@ int SolarisBackend::mixerProc() pollitem.fd = mFd; pollitem.events = POLLOUT; - unlock(); + dlock.unlock(); int pret{poll(&pollitem, 1, 1000)}; - lock(); + dlock.lock(); if(pret < 0) { if(errno == EINTR || errno == EAGAIN) @@ -137,7 +137,6 @@ int SolarisBackend::mixerProc() write_ptr += wrote; } } - unlock(); return 0; } diff --git a/alc/backends/wasapi.cpp b/alc/backends/wasapi.cpp index b6f5b5fb..181518d0 100644 --- a/alc/backends/wasapi.cpp +++ b/alc/backends/wasapi.cpp @@ -689,10 +689,10 @@ FORCE_ALIGN int WasapiPlayback::mixerProc() hr = mRender->GetBuffer(len, &buffer); if(SUCCEEDED(hr)) { - lock(); + std::unique_lock dlock{*this}; aluMixData(mDevice, buffer, len); mPadding.store(written + len, std::memory_order_relaxed); - unlock(); + dlock.unlock(); hr = mRender->ReleaseBuffer(len, 0); } if(FAILED(hr)) @@ -1136,11 +1136,10 @@ ClockLatency WasapiPlayback::getClockLatency() { ClockLatency ret; - lock(); + std::lock_guard _{*this}; ret.ClockTime = GetDeviceClockTime(mDevice); ret.Latency = std::chrono::seconds{mPadding.load(std::memory_order_relaxed)}; ret.Latency /= mDevice->Frequency; - unlock(); return ret; } diff --git a/alc/backends/wave.cpp b/alc/backends/wave.cpp index 927cb276..3b0a30d8 100644 --- a/alc/backends/wave.cpp +++ b/alc/backends/wave.cpp @@ -145,9 +145,10 @@ int WaveBackend::mixerProc() } while(avail-done >= mDevice->UpdateSize) { - lock(); - aluMixData(mDevice, mBuffer.data(), mDevice->UpdateSize); - unlock(); + { + std::lock_guard _{*this}; + aluMixData(mDevice, mBuffer.data(), mDevice->UpdateSize); + } done += mDevice->UpdateSize; if(!IS_LITTLE_ENDIAN) diff --git a/alc/backends/winmm.cpp b/alc/backends/winmm.cpp index c287e136..8f85f351 100644 --- a/alc/backends/winmm.cpp +++ b/alc/backends/winmm.cpp @@ -183,16 +183,16 @@ FORCE_ALIGN int WinMMPlayback::mixerProc() SetRTPriority(); althrd_setname(MIXER_THREAD_NAME); - lock(); + std::unique_lock dlock{*this}; while(!mKillNow.load(std::memory_order_acquire) && mDevice->Connected.load(std::memory_order_acquire)) { ALsizei todo = mWritable.load(std::memory_order_acquire); if(todo < 1) { - unlock(); + dlock.unlock(); mSem.wait(); - lock(); + dlock.lock(); continue; } @@ -207,7 +207,6 @@ FORCE_ALIGN int WinMMPlayback::mixerProc() } while(--todo); mIdx = static_cast(widx); } - unlock(); return 0; } @@ -427,16 +426,16 @@ int WinMMCapture::captureProc() { althrd_setname(RECORD_THREAD_NAME); - lock(); + std::unique_lock dlock{*this}; while(!mKillNow.load(std::memory_order_acquire) && mDevice->Connected.load(std::memory_order_acquire)) { ALuint todo{mReadable.load(std::memory_order_acquire)}; if(todo < 1) { - unlock(); + dlock.unlock(); mSem.wait(); - lock(); + dlock.lock(); continue; } @@ -451,7 +450,6 @@ int WinMMCapture::captureProc() } while(--todo); mIdx = static_cast(widx); } - unlock(); return 0; } -- cgit v1.2.3 From 7726a06d26e59dc6a8e109af2e268de878c4f606 Mon Sep 17 00:00:00 2001 From: Chris Robinson Date: Tue, 8 Oct 2019 05:44:38 -0700 Subject: Clean up some exception messages and avoid duplicate log messages --- alc/backends/alsa.cpp | 16 +++----------- alc/backends/coreaudio.cpp | 54 ++------------------------------------------- alc/backends/dsound.cpp | 5 ----- alc/backends/jack.cpp | 6 ++--- alc/backends/opensl.cpp | 12 +++++----- alc/backends/oss.cpp | 46 +++++++++----------------------------- alc/backends/portaudio.cpp | 5 ----- alc/backends/pulseaudio.cpp | 2 +- alc/backends/sdl2.cpp | 12 ++++------ alc/backends/sndio.cpp | 47 +++++++++++---------------------------- alc/backends/solaris.cpp | 3 --- alc/backends/wasapi.cpp | 2 -- alc/backends/wave.cpp | 3 --- alc/backends/winmm.cpp | 17 ++++---------- 14 files changed, 46 insertions(+), 184 deletions(-) (limited to 'alc/backends/alsa.cpp') diff --git a/alc/backends/alsa.cpp b/alc/backends/alsa.cpp index a9eb6d5f..7c6ce4f9 100644 --- a/alc/backends/alsa.cpp +++ b/alc/backends/alsa.cpp @@ -616,11 +616,8 @@ void AlsaPlayback::open(const ALCchar *name) TRACE("Opening device \"%s\"\n", driver); int err{snd_pcm_open(&mPcmHandle, driver, SND_PCM_STREAM_PLAYBACK, SND_PCM_NONBLOCK)}; if(err < 0) - { - ERR("Could not open playback device '%s': %s\n", driver, snd_strerror(err)); - throw al::backend_exception{ALC_OUT_OF_MEMORY, "Could not open ALSA playback \"%s\"", + throw al::backend_exception{ALC_OUT_OF_MEMORY, "Could not open ALSA device \"%s\"", driver}; - } /* Free alsa's global config tree. Otherwise valgrind reports a ton of leaks. */ snd_config_update_free_global(); @@ -917,11 +914,8 @@ void AlsaCapture::open(const ALCchar *name) TRACE("Opening device \"%s\"\n", driver); int err{snd_pcm_open(&mPcmHandle, driver, SND_PCM_STREAM_CAPTURE, SND_PCM_NONBLOCK)}; if(err < 0) - { - ERR("Could not open capture device '%s': %s\n", driver, snd_strerror(err)); - throw al::backend_exception{ALC_OUT_OF_MEMORY, "Could not open ALSA capture \"%s\"", + throw al::backend_exception{ALC_OUT_OF_MEMORY, "Could not open ALSA device \"%s\"", driver}; - } /* Free alsa's global config tree. Otherwise valgrind reports a ton of leaks. */ snd_config_update_free_global(); @@ -989,11 +983,7 @@ void AlsaCapture::open(const ALCchar *name) if(needring) { mRing = CreateRingBuffer(mDevice->BufferSize, mDevice->frameSizeFromFmt(), false); - if(!mRing) - { - ERR("ring buffer create failed\n"); - throw al::backend_exception{ALC_INVALID_VALUE, "Failed to create ring buffer"}; - } + if(!mRing) throw al::backend_exception{ALC_INVALID_VALUE, "Failed to create ring buffer"}; } mDevice->DeviceName = name; diff --git a/alc/backends/coreaudio.cpp b/alc/backends/coreaudio.cpp index 3a97c105..9e1d4e47 100644 --- a/alc/backends/coreaudio.cpp +++ b/alc/backends/coreaudio.cpp @@ -108,26 +108,17 @@ void CoreAudioPlayback::open(const ALCchar *name) AudioComponent comp{AudioComponentFindNext(NULL, &desc)}; if(comp == nullptr) - { - ERR("AudioComponentFindNext failed\n"); throw al::backend_exception{ALC_INVALID_VALUE, "Could not find audio component"}; - } OSStatus err{AudioComponentInstanceNew(comp, &mAudioUnit)}; if(err != noErr) - { - ERR("AudioComponentInstanceNew failed\n"); throw al::backend_exception{ALC_INVALID_VALUE, "Could not create component instance: %u", err}; - } /* init and start the default audio unit... */ err = AudioUnitInitialize(mAudioUnit); if(err != noErr) - { - ERR("AudioUnitInitialize failed\n"); throw al::backend_exception{ALC_INVALID_VALUE, "Could not initialize audio unit: %u", err}; - } mDevice->DeviceName = name; } @@ -418,41 +409,29 @@ void CoreAudioCapture::open(const ALCchar *name) // Search for component with given description comp = AudioComponentFindNext(NULL, &desc); if(comp == NULL) - { - ERR("AudioComponentFindNext failed\n"); - throw al::backend_exception{ALC_INVALID_VALUE, "Could not finda udio component"}; - } + throw al::backend_exception{ALC_INVALID_VALUE, "Could not find audio component"}; // Open the component err = AudioComponentInstanceNew(comp, &mAudioUnit); if(err != noErr) - { - ERR("AudioComponentInstanceNew failed\n"); throw al::backend_exception{ALC_INVALID_VALUE, "Could not create component instance: %u", err}; - } // Turn off AudioUnit output enableIO = 0; err = AudioUnitSetProperty(mAudioUnit, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Output, 0, &enableIO, sizeof(ALuint)); if(err != noErr) - { - ERR("AudioUnitSetProperty failed\n"); throw al::backend_exception{ALC_INVALID_VALUE, "Could not disable audio unit output property: %u", err}; - } // Turn on AudioUnit input enableIO = 1; err = AudioUnitSetProperty(mAudioUnit, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Input, 1, &enableIO, sizeof(ALuint)); if(err != noErr) - { - ERR("AudioUnitSetProperty failed\n"); throw al::backend_exception{ALC_INVALID_VALUE, "Could not enable audio unit input property: %u", err}; - } #if !TARGET_OS_IOS { @@ -467,24 +446,15 @@ void CoreAudioCapture::open(const ALCchar *name) err = AudioObjectGetPropertyData(kAudioObjectSystemObject, &propertyAddress, 0, nullptr, &propertySize, &inputDevice); if(err != noErr) - { - ERR("AudioObjectGetPropertyData failed\n"); throw al::backend_exception{ALC_INVALID_VALUE, "Could not get input device: %u", err}; - } if(inputDevice == kAudioDeviceUnknown) - { - ERR("No input device found\n"); throw al::backend_exception{ALC_INVALID_VALUE, "Unknown input device"}; - } // Track the input device err = AudioUnitSetProperty(mAudioUnit, kAudioOutputUnitProperty_CurrentDevice, kAudioUnitScope_Global, 0, &inputDevice, sizeof(AudioDeviceID)); if(err != noErr) - { - ERR("AudioUnitSetProperty failed\n"); throw al::backend_exception{ALC_INVALID_VALUE, "Could not set input device: %u", err}; - } } #endif @@ -495,28 +465,19 @@ void CoreAudioCapture::open(const ALCchar *name) err = AudioUnitSetProperty(mAudioUnit, kAudioOutputUnitProperty_SetInputCallback, kAudioUnitScope_Global, 0, &input, sizeof(AURenderCallbackStruct)); if(err != noErr) - { - ERR("AudioUnitSetProperty failed\n"); throw al::backend_exception{ALC_INVALID_VALUE, "Could not set capture callback: %u", err}; - } // Initialize the device err = AudioUnitInitialize(mAudioUnit); if(err != noErr) - { - ERR("AudioUnitInitialize failed\n"); throw al::backend_exception{ALC_INVALID_VALUE, "Could not initialize audio unit: %u", err}; - } // Get the hardware format propertySize = sizeof(AudioStreamBasicDescription); err = AudioUnitGetProperty(mAudioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 1, &hardwareFormat, &propertySize); if(err != noErr || propertySize != sizeof(AudioStreamBasicDescription)) - { - ERR("AudioUnitGetProperty failed\n"); throw al::backend_exception{ALC_INVALID_VALUE, "Could not get input format: %u", err}; - } // Set up the requested format description switch(mDevice->FmtType) @@ -540,7 +501,6 @@ void CoreAudioCapture::open(const ALCchar *name) case DevFmtByte: case DevFmtUShort: case DevFmtUInt: - ERR("%s samples not supported\n", DevFmtTypeString(mDevice->FmtType)); throw al::backend_exception{ALC_INVALID_VALUE, "%s samples not suppoted", DevFmtTypeString(mDevice->FmtType)}; } @@ -560,7 +520,6 @@ void CoreAudioCapture::open(const ALCchar *name) case DevFmtX61: case DevFmtX71: case DevFmtAmbi3D: - ERR("%s not supported\n", DevFmtChannelsString(mDevice->FmtChans)); throw al::backend_exception{ALC_INVALID_VALUE, "%s not supported", DevFmtChannelsString(mDevice->FmtChans)}; } @@ -586,10 +545,7 @@ void CoreAudioCapture::open(const ALCchar *name) err = AudioUnitSetProperty(mAudioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &outputFormat, sizeof(outputFormat)); if(err != noErr) - { - ERR("AudioUnitSetProperty failed\n"); throw al::backend_exception{ALC_INVALID_VALUE, "Could not set input format: %u", err}; - } // Set the AudioUnit output format frame count uint64_t FrameCount64{mDevice->UpdateSize}; @@ -597,21 +553,15 @@ void CoreAudioCapture::open(const ALCchar *name) mDevice->Frequency; FrameCount64 += MAX_RESAMPLER_PADDING; if(FrameCount64 > std::numeric_limits::max()/2) - { - ERR("FrameCount too large\n"); throw al::backend_exception{ALC_INVALID_VALUE, - "Calculated frame count is too lareg: %" PRIu64, FrameCount64}; - } + "Calculated frame count is too large: %" PRIu64, FrameCount64}; outputFrameCount = static_cast(FrameCount64); err = AudioUnitSetProperty(mAudioUnit, kAudioUnitProperty_MaximumFramesPerSlice, kAudioUnitScope_Output, 0, &outputFrameCount, sizeof(outputFrameCount)); if(err != noErr) - { - ERR("AudioUnitSetProperty failed: %d\n", err); throw al::backend_exception{ALC_INVALID_VALUE, "Failed to set capture frame count: %u", err}; - } // Set up sample converter if needed if(outputFormat.mSampleRate != mDevice->Frequency) diff --git a/alc/backends/dsound.cpp b/alc/backends/dsound.cpp index d48b74e2..005c9584 100644 --- a/alc/backends/dsound.cpp +++ b/alc/backends/dsound.cpp @@ -341,10 +341,7 @@ void DSoundPlayback::open(const ALCchar *name) if(SUCCEEDED(hr)) hr = mDS->SetCooperativeLevel(GetForegroundWindow(), DSSCL_PRIORITY); if(FAILED(hr)) - { - ERR("Device init failed: 0x%08lx\n", hr); throw al::backend_exception{ALC_INVALID_VALUE, "Device init failed: 0x%08lx", hr}; - } mDevice->DeviceName = name; } @@ -753,8 +750,6 @@ void DSoundCapture::open(const ALCchar *name) if(FAILED(hr)) { - ERR("Device init failed: 0x%08lx\n", hr); - mRing = nullptr; if(mDSCbuffer) mDSCbuffer->Release(); diff --git a/alc/backends/jack.cpp b/alc/backends/jack.cpp index 7c3f1822..2a22ed84 100644 --- a/alc/backends/jack.cpp +++ b/alc/backends/jack.cpp @@ -336,11 +336,9 @@ void JackPlayback::open(const ALCchar *name) jack_status_t status; mClient = jack_client_open(client_name, ClientOptions, &status, nullptr); if(mClient == nullptr) - { - ERR("jack_client_open() failed, status = 0x%02x\n", status); - throw al::backend_exception{ALC_INVALID_VALUE, "Failed to connect to JACK server: 0x%02x", + throw al::backend_exception{ALC_INVALID_VALUE, "Failed to open client connection: 0x%02x", status}; - } + if((status&JackServerStarted)) TRACE("JACK server started\n"); if((status&JackNameNotUnique)) diff --git a/alc/backends/opensl.cpp b/alc/backends/opensl.cpp index f546f168..4e68da27 100644 --- a/alc/backends/opensl.cpp +++ b/alc/backends/opensl.cpp @@ -146,9 +146,9 @@ struct OpenSLPlayback final : public BackendBase { OpenSLPlayback(ALCdevice *device) noexcept : BackendBase{device} { } ~OpenSLPlayback() override; + void process(SLAndroidSimpleBufferQueueItf bq); static void processC(SLAndroidSimpleBufferQueueItf bq, void *context) { static_cast(context)->process(bq); } - void process(SLAndroidSimpleBufferQueueItf bq); int mixerProc(); @@ -339,8 +339,8 @@ void OpenSLPlayback::open(const ALCchar *name) mEngineObj = nullptr; mEngine = nullptr; - throw al::backend_exception{ALC_INVALID_VALUE, "Failed to initialize OpenSL: 0x%08x", - result}; + throw al::backend_exception{ALC_INVALID_VALUE, + "Failed to initialize OpenSL device: 0x%08x", result}; } mDevice->DeviceName = name; @@ -629,9 +629,9 @@ struct OpenSLCapture final : public BackendBase { OpenSLCapture(ALCdevice *device) noexcept : BackendBase{device} { } ~OpenSLCapture() override; + void process(SLAndroidSimpleBufferQueueItf bq); static void processC(SLAndroidSimpleBufferQueueItf bq, void *context) { static_cast(context)->process(bq); } - void process(SLAndroidSimpleBufferQueueItf bq); void open(const ALCchar *name) override; bool start() override; @@ -839,8 +839,8 @@ void OpenSLCapture::open(const ALCchar* name) mEngineObj = nullptr; mEngine = nullptr; - throw al::backend_exception{ALC_INVALID_VALUE, "Failed to initialize OpenSL: 0x%08x", - result}; + throw al::backend_exception{ALC_INVALID_VALUE, + "Failed to initialize OpenSL device: 0x%08x", result}; } mDevice->DeviceName = name; diff --git a/alc/backends/oss.cpp b/alc/backends/oss.cpp index 5ab07dbe..856aceb0 100644 --- a/alc/backends/oss.cpp +++ b/alc/backends/oss.cpp @@ -350,11 +350,8 @@ void OSSPlayback::open(const ALCchar *name) mFd = ::open(devname, O_WRONLY); if(mFd == -1) - { - ERR("Could not open %s: %s\n", devname, strerror(errno)); throw al::backend_exception{ALC_INVALID_VALUE, "Could not open %s: %s", devname, strerror(errno)}; - } mDevice->DeviceName = name; } @@ -560,11 +557,8 @@ void OSScapture::open(const ALCchar *name) mFd = ::open(devname, O_RDONLY); if(mFd == -1) - { - ERR("Could not open %s: %s\n", devname, strerror(errno)); throw al::backend_exception{ALC_INVALID_VALUE, "Could not open %s: %s", devname, strerror(errno)}; - } int ossFormat{}; switch(mDevice->FmtType) @@ -582,7 +576,6 @@ void OSScapture::open(const ALCchar *name) case DevFmtInt: case DevFmtUInt: case DevFmtFloat: - ERR("%s capture samples not supported\n", DevFmtTypeString(mDevice->FmtType)); throw al::backend_exception{ALC_INVALID_VALUE, "%s capture samples not supported", DevFmtTypeString(mDevice->FmtType)}; } @@ -596,47 +589,30 @@ void OSScapture::open(const ALCchar *name) ALuint numFragmentsLogSize{(periods << 16) | log2FragmentSize}; audio_buf_info info{}; - const char *err; #define CHECKERR(func) if((func) < 0) { \ - err = #func; \ - goto err; \ + throw al::backend_exception{ALC_INVALID_VALUE, #func " failed: %s", strerror(errno)}; \ } CHECKERR(ioctl(mFd, SNDCTL_DSP_SETFRAGMENT, &numFragmentsLogSize)); CHECKERR(ioctl(mFd, SNDCTL_DSP_SETFMT, &ossFormat)); CHECKERR(ioctl(mFd, SNDCTL_DSP_CHANNELS, &numChannels)); CHECKERR(ioctl(mFd, SNDCTL_DSP_SPEED, &ossSpeed)); CHECKERR(ioctl(mFd, SNDCTL_DSP_GETISPACE, &info)); - if(0) - { - err: - ERR("%s failed: %s\n", err, strerror(errno)); - throw al::backend_exception{ALC_INVALID_VALUE, "%s failed: %s", err, strerror(errno)}; - } #undef CHECKERR if(mDevice->channelsFromFmt() != numChannels) - { - ERR("Failed to set %s, got %d channels instead\n", DevFmtChannelsString(mDevice->FmtChans), - numChannels); - throw al::backend_exception{ALC_INVALID_VALUE, "Failed to set %s capture", - DevFmtChannelsString(mDevice->FmtChans)}; - } + throw al::backend_exception{ALC_INVALID_VALUE, + "Failed to set %s, got %d channels instead", DevFmtChannelsString(mDevice->FmtChans), + numChannels}; - if(!((ossFormat == AFMT_S8 && mDevice->FmtType == DevFmtByte) || - (ossFormat == AFMT_U8 && mDevice->FmtType == DevFmtUByte) || - (ossFormat == AFMT_S16_NE && mDevice->FmtType == DevFmtShort))) - { - ERR("Failed to set %s samples, got OSS format %#x\n", DevFmtTypeString(mDevice->FmtType), ossFormat); - throw al::backend_exception{ALC_INVALID_VALUE, "Failed to set %s samples", - DevFmtTypeString(mDevice->FmtType)}; - } + if(!((ossFormat == AFMT_S8 && mDevice->FmtType == DevFmtByte) + || (ossFormat == AFMT_U8 && mDevice->FmtType == DevFmtUByte) + || (ossFormat == AFMT_S16_NE && mDevice->FmtType == DevFmtShort))) + throw al::backend_exception{ALC_INVALID_VALUE, + "Failed to set %s samples, got OSS format %#x", DevFmtTypeString(mDevice->FmtType), + ossFormat}; mRing = CreateRingBuffer(mDevice->BufferSize, frameSize, false); - if(!mRing) - { - ERR("Ring buffer create failed\n"); - throw al::backend_exception{ALC_INVALID_VALUE, "Failed to create ring buffer"}; - } + if(!mRing) throw al::backend_exception{ALC_INVALID_VALUE, "Failed to create ring buffer"}; mDevice->DeviceName = name; } diff --git a/alc/backends/portaudio.cpp b/alc/backends/portaudio.cpp index ba8e4984..7c60d2bb 100644 --- a/alc/backends/portaudio.cpp +++ b/alc/backends/portaudio.cpp @@ -166,7 +166,6 @@ retry_open: mParams.sampleFormat = paInt16; goto retry_open; } - ERR("Pa_OpenStream() returned an error: %s\n", Pa_GetErrorText(err)); throw al::backend_exception{ALC_INVALID_VALUE, "Failed to open stream: %s", Pa_GetErrorText(err)}; } @@ -314,7 +313,6 @@ void PortCapture::open(const ALCchar *name) break; case DevFmtUInt: case DevFmtUShort: - ERR("%s samples not supported\n", DevFmtTypeString(mDevice->FmtType)); throw al::backend_exception{ALC_INVALID_VALUE, "%s samples not supported", DevFmtTypeString(mDevice->FmtType)}; } @@ -323,11 +321,8 @@ void PortCapture::open(const ALCchar *name) PaError err{Pa_OpenStream(&mStream, &mParams, nullptr, mDevice->Frequency, paFramesPerBufferUnspecified, paNoFlag, &PortCapture::readCallbackC, this)}; if(err != paNoError) - { - ERR("Pa_OpenStream() returned an error: %s\n", Pa_GetErrorText(err)); throw al::backend_exception{ALC_INVALID_VALUE, "Failed to open stream: %s", Pa_GetErrorText(err)}; - } mDevice->DeviceName = name; } diff --git a/alc/backends/pulseaudio.cpp b/alc/backends/pulseaudio.cpp index e4b1baa2..2521084d 100644 --- a/alc/backends/pulseaudio.cpp +++ b/alc/backends/pulseaudio.cpp @@ -1211,7 +1211,7 @@ void PulseCapture::open(const ALCchar *name) chanmap = X71ChanMap; break; case DevFmtAmbi3D: - throw al::backend_exception{ALC_INVALID_VALUE, "%s capture samples not supported", + throw al::backend_exception{ALC_INVALID_VALUE, "%s capture not supported", DevFmtChannelsString(mDevice->FmtChans)}; } SetChannelOrderFromMap(mDevice, chanmap); diff --git a/alc/backends/sdl2.cpp b/alc/backends/sdl2.cpp index 1063ca7a..4cdf05b4 100644 --- a/alc/backends/sdl2.cpp +++ b/alc/backends/sdl2.cpp @@ -52,8 +52,9 @@ struct Sdl2Backend final : public BackendBase { Sdl2Backend(ALCdevice *device) noexcept : BackendBase{device} { } ~Sdl2Backend() override; - static void audioCallbackC(void *ptr, Uint8 *stream, int len); void audioCallback(Uint8 *stream, int len); + static void audioCallbackC(void *ptr, Uint8 *stream, int len) + { static_cast(ptr)->audioCallback(stream, len); } void open(const ALCchar *name) override; bool reset() override; @@ -80,9 +81,6 @@ Sdl2Backend::~Sdl2Backend() mDeviceID = 0; } -void Sdl2Backend::audioCallbackC(void *ptr, Uint8 *stream, int len) -{ static_cast(ptr)->audioCallback(stream, len); } - void Sdl2Backend::audioCallback(Uint8 *stream, int len) { const auto ulen = static_cast(len); @@ -130,16 +128,15 @@ void Sdl2Backend::open(const ALCchar *name) throw al::backend_exception{ALC_INVALID_VALUE, "%s", SDL_GetError()}; mDevice->Frequency = static_cast(have.freq); + if(have.channels == 1) mDevice->FmtChans = DevFmtMono; else if(have.channels == 2) mDevice->FmtChans = DevFmtStereo; else - { - ERR("Got unhandled SDL channel count: %d\n", int{have.channels}); throw al::backend_exception{ALC_INVALID_VALUE, "Unhandled SDL channel count: %d", int{have.channels}}; - } + switch(have.format) { case AUDIO_U8: mDevice->FmtType = DevFmtUByte; break; @@ -149,7 +146,6 @@ void Sdl2Backend::open(const ALCchar *name) case AUDIO_S32SYS: mDevice->FmtType = DevFmtInt; break; case AUDIO_F32SYS: mDevice->FmtType = DevFmtFloat; break; default: - ERR("Got unsupported SDL format: 0x%04x\n", have.format); throw al::backend_exception{ALC_INVALID_VALUE, "Unhandled SDL format: 0x%04x", have.format}; } diff --git a/alc/backends/sndio.cpp b/alc/backends/sndio.cpp index 5657a241..026ff2b9 100644 --- a/alc/backends/sndio.cpp +++ b/alc/backends/sndio.cpp @@ -117,10 +117,7 @@ void SndioPlayback::open(const ALCchar *name) mSndHandle = sio_open(nullptr, SIO_PLAY, 0); if(mSndHandle == nullptr) - { - ERR("Could not open device\n"); - throw al::backend_exception{ALC_INVALID_VALUE, "Could not open sound device"}; - } + throw al::backend_exception{ALC_INVALID_VALUE, "Could not open backend device"}; mDevice->DeviceName = name; } @@ -329,10 +326,7 @@ void SndioCapture::open(const ALCchar *name) mSndHandle = sio_open(nullptr, SIO_REC, 0); if(mSndHandle == nullptr) - { - ERR("Could not open device\n"); - throw al::backend_exception{ALC_INVALID_VALUE, "Could not open sound device"}; - } + throw al::backend_exception{ALC_INVALID_VALUE, "Could not open backend device"}; sio_par par; sio_initpar(&par); @@ -364,7 +358,6 @@ void SndioCapture::open(const ALCchar *name) par.sig = 0; break; case DevFmtFloat: - ERR("%s capture samples not supported\n", DevFmtTypeString(mDevice->FmtType)); throw al::backend_exception{ALC_INVALID_VALUE, "%s capture samples not supported", DevFmtTypeString(mDevice->FmtType)}; } @@ -381,40 +374,26 @@ void SndioCapture::open(const ALCchar *name) mDevice->BufferSize = par.appbufsz; if(!sio_setpar(mSndHandle, &par) || !sio_getpar(mSndHandle, &par)) - { - ERR("Failed to set device parameters\n"); throw al::backend_exception{ALC_INVALID_VALUE, "Failed to set device praameters"}; - } if(par.bits != par.bps*8) - { - ERR("Padded samples not supported (%u of %u bits)\n", par.bits, par.bps*8); throw al::backend_exception{ALC_INVALID_VALUE, "Padded samples not supported (got %u of %u bits)", par.bits, par.bps*8}; - } - if(!((mDevice->FmtType == DevFmtByte && par.bits == 8 && par.sig != 0) || - (mDevice->FmtType == DevFmtUByte && par.bits == 8 && par.sig == 0) || - (mDevice->FmtType == DevFmtShort && par.bits == 16 && par.sig != 0) || - (mDevice->FmtType == DevFmtUShort && par.bits == 16 && par.sig == 0) || - (mDevice->FmtType == DevFmtInt && par.bits == 32 && par.sig != 0) || - (mDevice->FmtType == DevFmtUInt && par.bits == 32 && par.sig == 0)) || - mDevice->channelsFromFmt() != par.rchan || mDevice->Frequency != par.rate) - { - ERR("Failed to set format %s %s %uhz, got %c%u %u-channel %uhz instead\n", - DevFmtTypeString(mDevice->FmtType), DevFmtChannelsString(mDevice->FmtChans), - mDevice->Frequency, par.sig?'s':'u', par.bits, par.rchan, par.rate); - throw al::backend_exception{ALC_INVALID_VALUE, "Could not set format %s %s %uhz", + if(!((mDevice->FmtType == DevFmtByte && par.bits == 8 && par.sig != 0) + || (mDevice->FmtType == DevFmtUByte && par.bits == 8 && par.sig == 0) + || (mDevice->FmtType == DevFmtShort && par.bits == 16 && par.sig != 0) + || (mDevice->FmtType == DevFmtUShort && par.bits == 16 && par.sig == 0) + || (mDevice->FmtType == DevFmtInt && par.bits == 32 && par.sig != 0) + || (mDevice->FmtType == DevFmtUInt && par.bits == 32 && par.sig == 0)) + || mDevice->channelsFromFmt() != par.rchan || mDevice->Frequency != par.rate) + throw al::backend_exception{ALC_INVALID_VALUE, + "Failed to set format %s %s %uhz, got %c%u %u-channel %uhz instead", DevFmtTypeString(mDevice->FmtType), DevFmtChannelsString(mDevice->FmtChans), - mDevice->Frequency}; - } + mDevice->Frequency, par.sig?'s':'u', par.bits, par.rchan, par.rate}; mRing = CreateRingBuffer(mDevice->BufferSize, par.bps*par.rchan, false); - if(!mRing) - { - ERR("Failed to allocate %u-byte ringbuffer\n", mDevice->BufferSize*par.bps*par.rchan); - throw al::backend_exception{ALC_OUT_OF_MEMORY, "Failed to allocate ring buffer"}; - } + if(!mRing) throw al::backend_exception{ALC_OUT_OF_MEMORY, "Failed to allocate ring buffer"}; SetDefaultChannelOrder(mDevice); diff --git a/alc/backends/solaris.cpp b/alc/backends/solaris.cpp index 79cc224d..7cc2606e 100644 --- a/alc/backends/solaris.cpp +++ b/alc/backends/solaris.cpp @@ -151,11 +151,8 @@ void SolarisBackend::open(const ALCchar *name) mFd = ::open(solaris_driver.c_str(), O_WRONLY); if(mFd == -1) - { - ERR("Could not open %s: %s\n", solaris_driver.c_str(), strerror(errno)); throw al::backend_exception{ALC_INVALID_VALUE, "Could not open %s: %s", solaris_driver.c_str(), strerror(errno)}; - } mDevice->DeviceName = name; } diff --git a/alc/backends/wasapi.cpp b/alc/backends/wasapi.cpp index 181518d0..2c4fe130 100644 --- a/alc/backends/wasapi.cpp +++ b/alc/backends/wasapi.cpp @@ -762,7 +762,6 @@ void WasapiPlayback::open(const ALCchar *name) mDevId.clear(); - ERR("Device init failed: 0x%08lx\n", hr); throw al::backend_exception{ALC_INVALID_VALUE, "Device init failed: 0x%08lx", hr}; } } @@ -1336,7 +1335,6 @@ void WasapiCapture::open(const ALCchar *name) mDevId.clear(); - ERR("Device init failed: 0x%08lx\n", hr); throw al::backend_exception{ALC_INVALID_VALUE, "Device init failed: 0x%08lx", hr}; } diff --git a/alc/backends/wave.cpp b/alc/backends/wave.cpp index 3b0a30d8..7bcc3436 100644 --- a/alc/backends/wave.cpp +++ b/alc/backends/wave.cpp @@ -223,11 +223,8 @@ void WaveBackend::open(const ALCchar *name) mFile = fopen(fname, "wb"); #endif if(!mFile) - { - ERR("Could not open file '%s': %s\n", fname, strerror(errno)); throw al::backend_exception{ALC_INVALID_VALUE, "Could not open file '%s': %s", fname, strerror(errno)}; - } mDevice->DeviceName = name; } diff --git a/alc/backends/winmm.cpp b/alc/backends/winmm.cpp index 8f85f351..dde74304 100644 --- a/alc/backends/winmm.cpp +++ b/alc/backends/winmm.cpp @@ -127,8 +127,9 @@ struct WinMMPlayback final : public BackendBase { WinMMPlayback(ALCdevice *device) noexcept : BackendBase{device} { } ~WinMMPlayback() override; - static void CALLBACK waveOutProcC(HWAVEOUT device, UINT msg, DWORD_PTR instance, DWORD_PTR param1, DWORD_PTR param2); void CALLBACK waveOutProc(HWAVEOUT device, UINT msg, DWORD_PTR param1, DWORD_PTR param2); + static void CALLBACK waveOutProcC(HWAVEOUT device, UINT msg, DWORD_PTR instance, DWORD_PTR param1, DWORD_PTR param2) + { reinterpret_cast(instance)->waveOutProc(device, msg, param1, param2); } int mixerProc(); @@ -162,10 +163,6 @@ WinMMPlayback::~WinMMPlayback() std::fill(mWaveBuffer.begin(), mWaveBuffer.end(), WAVEHDR{}); } - -void CALLBACK WinMMPlayback::waveOutProcC(HWAVEOUT device, UINT msg, DWORD_PTR instance, DWORD_PTR param1, DWORD_PTR param2) -{ reinterpret_cast(instance)->waveOutProc(device, msg, param1, param2); } - /* WinMMPlayback::waveOutProc * * Posts a message to 'WinMMPlayback::mixerProc' everytime a WaveOut Buffer is @@ -256,7 +253,6 @@ retry_open: mDevice->FmtType = DevFmtShort; goto retry_open; } - ERR("waveOutOpen failed: %u\n", res); throw al::backend_exception{ALC_INVALID_VALUE, "waveOutOpen failed: %u", res}; } @@ -368,8 +364,9 @@ struct WinMMCapture final : public BackendBase { WinMMCapture(ALCdevice *device) noexcept : BackendBase{device} { } ~WinMMCapture() override; - static void CALLBACK waveInProcC(HWAVEIN device, UINT msg, DWORD_PTR instance, DWORD_PTR param1, DWORD_PTR param2); void CALLBACK waveInProc(HWAVEIN device, UINT msg, DWORD_PTR param1, DWORD_PTR param2); + static void CALLBACK waveInProcC(HWAVEIN device, UINT msg, DWORD_PTR instance, DWORD_PTR param1, DWORD_PTR param2) + { reinterpret_cast(instance)->waveInProc(device, msg, param1, param2); } int captureProc(); @@ -407,9 +404,6 @@ WinMMCapture::~WinMMCapture() std::fill(mWaveBuffer.begin(), mWaveBuffer.end(), WAVEHDR{}); } -void CALLBACK WinMMCapture::waveInProcC(HWAVEIN device, UINT msg, DWORD_PTR instance, DWORD_PTR param1, DWORD_PTR param2) -{ reinterpret_cast(instance)->waveInProc(device, msg, param1, param2); } - /* WinMMCapture::waveInProc * * Posts a message to 'WinMMCapture::captureProc' everytime a WaveIn Buffer is @@ -513,10 +507,7 @@ void WinMMCapture::open(const ALCchar *name) reinterpret_cast(&WinMMCapture::waveInProcC), reinterpret_cast(this), CALLBACK_FUNCTION)}; if(res != MMSYSERR_NOERROR) - { - ERR("waveInOpen failed: %u\n", res); throw al::backend_exception{ALC_INVALID_VALUE, "waveInOpen failed: %u", res}; - } // Ensure each buffer is 50ms each DWORD BufferSize{mFormat.nAvgBytesPerSec / 20u}; -- cgit v1.2.3 From 963580c2d503eab7c6d8f60a367498ff103bfa3e Mon Sep 17 00:00:00 2001 From: Chris Robinson Date: Tue, 8 Oct 2019 21:52:08 -0700 Subject: Never return null from CreateRingBuffer Allocation failure would already throw a bad_alloc anyway, now a size overflow throws an exception too. --- alc/backends/alsa.cpp | 3 --- alc/backends/coreaudio.cpp | 1 - alc/backends/dsound.cpp | 3 --- alc/backends/jack.cpp | 11 +---------- alc/backends/opensl.cpp | 21 ++++----------------- alc/backends/oss.cpp | 1 - alc/backends/portaudio.cpp | 1 - alc/backends/sndio.cpp | 1 - alc/backends/wasapi.cpp | 5 ----- alc/backends/winmm.cpp | 1 - alc/ringbuffer.cpp | 4 +++- 11 files changed, 8 insertions(+), 44 deletions(-) (limited to 'alc/backends/alsa.cpp') diff --git a/alc/backends/alsa.cpp b/alc/backends/alsa.cpp index 7c6ce4f9..91415c32 100644 --- a/alc/backends/alsa.cpp +++ b/alc/backends/alsa.cpp @@ -981,10 +981,7 @@ void AlsaCapture::open(const ALCchar *name) hp = nullptr; if(needring) - { mRing = CreateRingBuffer(mDevice->BufferSize, mDevice->frameSizeFromFmt(), false); - if(!mRing) throw al::backend_exception{ALC_INVALID_VALUE, "Failed to create ring buffer"}; - } mDevice->DeviceName = name; return; diff --git a/alc/backends/coreaudio.cpp b/alc/backends/coreaudio.cpp index 9e1d4e47..5a0e4027 100644 --- a/alc/backends/coreaudio.cpp +++ b/alc/backends/coreaudio.cpp @@ -570,7 +570,6 @@ void CoreAudioCapture::open(const ALCchar *name) mDevice->Frequency, Resampler::FastBSinc24); mRing = CreateRingBuffer(outputFrameCount, mFrameSize, false); - if(!mRing) throw al::backend_exception{ALC_INVALID_VALUE, "Failed to allocate ring buffer"}; mDevice->DeviceName = name; } diff --git a/alc/backends/dsound.cpp b/alc/backends/dsound.cpp index 005c9584..b74f2d3e 100644 --- a/alc/backends/dsound.cpp +++ b/alc/backends/dsound.cpp @@ -743,10 +743,7 @@ void DSoundCapture::open(const ALCchar *name) if(SUCCEEDED(hr)) mDSC->CreateCaptureBuffer(&DSCBDescription, &mDSCbuffer, nullptr); if(SUCCEEDED(hr)) - { mRing = CreateRingBuffer(mDevice->BufferSize, InputType.Format.nBlockAlign, false); - if(!mRing) hr = DSERR_OUTOFMEMORY; - } if(FAILED(hr)) { diff --git a/alc/backends/jack.cpp b/alc/backends/jack.cpp index 2a22ed84..0814ca8d 100644 --- a/alc/backends/jack.cpp +++ b/alc/backends/jack.cpp @@ -212,11 +212,7 @@ int JackPlayback::bufferSizeNotify(jack_nframes_t numframes) mRing = nullptr; mRing = CreateRingBuffer(bufsize, mDevice->frameSizeFromFmt(), true); - if(!mRing) - { - ERR("Failed to reallocate ringbuffer\n"); - aluHandleDisconnect(mDevice, "Failed to reallocate %u-sample buffer", bufsize); - } + return 0; } @@ -407,11 +403,6 @@ bool JackPlayback::reset() mRing = nullptr; mRing = CreateRingBuffer(bufsize, mDevice->frameSizeFromFmt(), true); - if(!mRing) - { - ERR("Failed to allocate ringbuffer\n"); - return false; - } SetDefaultChannelOrder(mDevice); diff --git a/alc/backends/opensl.cpp b/alc/backends/opensl.cpp index 4e68da27..258443f2 100644 --- a/alc/backends/opensl.cpp +++ b/alc/backends/opensl.cpp @@ -521,14 +521,7 @@ bool OpenSLPlayback::reset() if(SL_RESULT_SUCCESS == result) { const ALuint num_updates{mDevice->BufferSize / mDevice->UpdateSize}; - try { - mRing = CreateRingBuffer(num_updates, mFrameSize*mDevice->UpdateSize, true); - } - catch(std::exception& e) { - ERR("Failed allocating ring buffer %ux%ux%u: %s\n", mDevice->UpdateSize, - num_updates, mFrameSize, e.what()); - result = SL_RESULT_MEMORY_FAILURE; - } + mRing = CreateRingBuffer(num_updates, mFrameSize*mDevice->UpdateSize, true); } if(SL_RESULT_SUCCESS != result) @@ -703,16 +696,10 @@ void OpenSLCapture::open(const ALCchar* name) mDevice->Frequency/100*5)}; ALuint num_updates{(length+update_len-1) / update_len}; - try { - mRing = CreateRingBuffer(num_updates, update_len*mFrameSize, false); + mRing = CreateRingBuffer(num_updates, update_len*mFrameSize, false); - mDevice->UpdateSize = update_len; - mDevice->BufferSize = static_cast(mRing->writeSpace() * update_len); - } - catch(std::exception& e) { - ERR("Failed to allocate ring buffer: %s\n", e.what()); - result = SL_RESULT_MEMORY_FAILURE; - } + mDevice->UpdateSize = update_len; + mDevice->BufferSize = static_cast(mRing->writeSpace() * update_len); } if(SL_RESULT_SUCCESS == result) { diff --git a/alc/backends/oss.cpp b/alc/backends/oss.cpp index 856aceb0..59cc44e4 100644 --- a/alc/backends/oss.cpp +++ b/alc/backends/oss.cpp @@ -612,7 +612,6 @@ void OSScapture::open(const ALCchar *name) ossFormat}; mRing = CreateRingBuffer(mDevice->BufferSize, frameSize, false); - if(!mRing) throw al::backend_exception{ALC_INVALID_VALUE, "Failed to create ring buffer"}; mDevice->DeviceName = name; } diff --git a/alc/backends/portaudio.cpp b/alc/backends/portaudio.cpp index 7c60d2bb..f50f1f16 100644 --- a/alc/backends/portaudio.cpp +++ b/alc/backends/portaudio.cpp @@ -286,7 +286,6 @@ void PortCapture::open(const ALCchar *name) ALuint frame_size{mDevice->frameSizeFromFmt()}; mRing = CreateRingBuffer(samples, frame_size, false); - if(!mRing) throw al::backend_exception{ALC_INVALID_VALUE, "Failed to create ring buffer"}; auto devidopt = ConfigValueInt(nullptr, "port", "capture"); if(devidopt && *devidopt >= 0) mParams.device = *devidopt; diff --git a/alc/backends/sndio.cpp b/alc/backends/sndio.cpp index 026ff2b9..7799316f 100644 --- a/alc/backends/sndio.cpp +++ b/alc/backends/sndio.cpp @@ -393,7 +393,6 @@ void SndioCapture::open(const ALCchar *name) mDevice->Frequency, par.sig?'s':'u', par.bits, par.rchan, par.rate}; mRing = CreateRingBuffer(mDevice->BufferSize, par.bps*par.rchan, false); - if(!mRing) throw al::backend_exception{ALC_OUT_OF_MEMORY, "Failed to allocate ring buffer"}; SetDefaultChannelOrder(mDevice); diff --git a/alc/backends/wasapi.cpp b/alc/backends/wasapi.cpp index 2c4fe130..37a547af 100644 --- a/alc/backends/wasapi.cpp +++ b/alc/backends/wasapi.cpp @@ -1601,11 +1601,6 @@ HRESULT WasapiCapture::resetProxy() buffer_len = maxu(mDevice->BufferSize, buffer_len); mRing = CreateRingBuffer(buffer_len, mDevice->frameSizeFromFmt(), false); - if(!mRing) - { - ERR("Failed to allocate capture ring buffer\n"); - return E_OUTOFMEMORY; - } hr = mClient->SetEventHandle(mNotifyEvent); if(FAILED(hr)) diff --git a/alc/backends/winmm.cpp b/alc/backends/winmm.cpp index dde74304..c2ccbc05 100644 --- a/alc/backends/winmm.cpp +++ b/alc/backends/winmm.cpp @@ -519,7 +519,6 @@ void WinMMCapture::open(const ALCchar *name) CapturedDataSize = static_cast(maxz(CapturedDataSize, BufferSize*mWaveBuffer.size())); mRing = CreateRingBuffer(CapturedDataSize, mFormat.nBlockAlign, false); - if(!mRing) throw al::backend_exception{ALC_INVALID_VALUE, "Could not create ring buffer"}; al_free(mWaveBuffer[0].lpData); mWaveBuffer[0] = WAVEHDR{}; diff --git a/alc/ringbuffer.cpp b/alc/ringbuffer.cpp index d61f6129..1f72f4b1 100644 --- a/alc/ringbuffer.cpp +++ b/alc/ringbuffer.cpp @@ -25,6 +25,7 @@ #include #include #include +#include #include "almalloc.h" @@ -45,7 +46,8 @@ RingBufferPtr CreateRingBuffer(size_t sz, size_t elem_sz, int limit_writes) #endif } ++power_of_two; - if(power_of_two < sz) return nullptr; + if(power_of_two <= sz || power_of_two > std::numeric_limits::max()/elem_sz) + throw std::overflow_error{"Ring buffer size overflow"}; const size_t bufbytes{power_of_two * elem_sz}; RingBufferPtr rb{new (FamCount{bufbytes}) RingBuffer{bufbytes}}; -- cgit v1.2.3 From a7c12453600d4e9ae756b933770c6f42977a2663 Mon Sep 17 00:00:00 2001 From: Chris Robinson Date: Wed, 9 Oct 2019 02:16:08 -0700 Subject: Use smart pointers for ALSA param handles And simplify some related error handling --- alc/backends/alsa.cpp | 260 +++++++++++++++++++++++++------------------------- 1 file changed, 128 insertions(+), 132 deletions(-) (limited to 'alc/backends/alsa.cpp') diff --git a/alc/backends/alsa.cpp b/alc/backends/alsa.cpp index 91415c32..1b8c6298 100644 --- a/alc/backends/alsa.cpp +++ b/alc/backends/alsa.cpp @@ -216,6 +216,29 @@ ALSA_FUNCS(MAKE_FUNC); #endif +struct HwParamsDeleter { + void operator()(snd_pcm_hw_params_t *ptr) { snd_pcm_hw_params_free(ptr); } +}; +using HwParamsPtr = std::unique_ptr; +HwParamsPtr CreateHwParams() +{ + snd_pcm_hw_params_t *hp{}; + snd_pcm_hw_params_malloc(&hp); + return HwParamsPtr{hp}; +} + +struct SwParamsDeleter { + void operator()(snd_pcm_sw_params_t *ptr) { snd_pcm_sw_params_free(ptr); } +}; +using SwParamsPtr = std::unique_ptr; +SwParamsPtr CreateSwParams() +{ + snd_pcm_sw_params_t *sp{}; + snd_pcm_sw_params_malloc(&sp); + return SwParamsPtr{sp}; +} + + struct DevMap { std::string name; std::string device_name; @@ -630,27 +653,27 @@ bool AlsaPlayback::reset() snd_pcm_format_t format{SND_PCM_FORMAT_UNKNOWN}; switch(mDevice->FmtType) { - case DevFmtByte: - format = SND_PCM_FORMAT_S8; - break; - case DevFmtUByte: - format = SND_PCM_FORMAT_U8; - break; - case DevFmtShort: - format = SND_PCM_FORMAT_S16; - break; - case DevFmtUShort: - format = SND_PCM_FORMAT_U16; - break; - case DevFmtInt: - format = SND_PCM_FORMAT_S32; - break; - case DevFmtUInt: - format = SND_PCM_FORMAT_U32; - break; - case DevFmtFloat: - format = SND_PCM_FORMAT_FLOAT; - break; + case DevFmtByte: + format = SND_PCM_FORMAT_S8; + break; + case DevFmtUByte: + format = SND_PCM_FORMAT_U8; + break; + case DevFmtShort: + format = SND_PCM_FORMAT_S16; + break; + case DevFmtUShort: + format = SND_PCM_FORMAT_U16; + break; + case DevFmtInt: + format = SND_PCM_FORMAT_S32; + break; + case DevFmtUInt: + format = SND_PCM_FORMAT_U32; + break; + case DevFmtFloat: + format = SND_PCM_FORMAT_FLOAT; + break; } bool allowmmap{!!GetConfigValueBool(mDevice->DeviceName.c_str(), "alsa", "mmap", 1)}; @@ -658,25 +681,22 @@ bool AlsaPlayback::reset() ALuint bufferLen{static_cast(mDevice->BufferSize * 1000000_u64 / mDevice->Frequency)}; ALuint rate{mDevice->Frequency}; - snd_pcm_uframes_t periodSizeInFrames{}; - snd_pcm_uframes_t bufferSizeInFrames{}; - snd_pcm_sw_params_t *sp{}; - snd_pcm_hw_params_t *hp{}; - snd_pcm_access_t access{}; - const char *funcerr{}; int err{}; - - snd_pcm_hw_params_malloc(&hp); -#define CHECK(x) if((funcerr=#x),(err=(x)) < 0) goto error - CHECK(snd_pcm_hw_params_any(mPcmHandle, hp)); + HwParamsPtr hp{CreateHwParams()}; +#define CHECK(x) do { \ + if((err=(x)) < 0) \ + throw al::backend_exception{ALC_INVALID_VALUE, #x " failed: %s", snd_strerror(err)}; \ +} while(0) + CHECK(snd_pcm_hw_params_any(mPcmHandle, hp.get())); /* set interleaved access */ - if(!allowmmap || snd_pcm_hw_params_set_access(mPcmHandle, hp, SND_PCM_ACCESS_MMAP_INTERLEAVED) < 0) + if(!allowmmap + || snd_pcm_hw_params_set_access(mPcmHandle, hp.get(), SND_PCM_ACCESS_MMAP_INTERLEAVED) < 0) { /* No mmap */ - CHECK(snd_pcm_hw_params_set_access(mPcmHandle, hp, SND_PCM_ACCESS_RW_INTERLEAVED)); + CHECK(snd_pcm_hw_params_set_access(mPcmHandle, hp.get(), SND_PCM_ACCESS_RW_INTERLEAVED)); } /* test and set format (implicitly sets sample bits) */ - if(snd_pcm_hw_params_test_format(mPcmHandle, hp, format) < 0) + if(snd_pcm_hw_params_test_format(mPcmHandle, hp.get(), format) < 0) { static const struct { snd_pcm_format_t format; @@ -694,16 +714,16 @@ bool AlsaPlayback::reset() for(const auto &fmt : formatlist) { format = fmt.format; - if(snd_pcm_hw_params_test_format(mPcmHandle, hp, format) >= 0) + if(snd_pcm_hw_params_test_format(mPcmHandle, hp.get(), format) >= 0) { mDevice->FmtType = fmt.fmttype; break; } } } - CHECK(snd_pcm_hw_params_set_format(mPcmHandle, hp, format)); + CHECK(snd_pcm_hw_params_set_format(mPcmHandle, hp.get(), format)); /* test and set channels (implicitly sets frame bits) */ - if(snd_pcm_hw_params_test_channels(mPcmHandle, hp, mDevice->channelsFromFmt()) < 0) + if(snd_pcm_hw_params_test_channels(mPcmHandle, hp.get(), mDevice->channelsFromFmt()) < 0) { static const DevFmtChannels channellist[] = { DevFmtStereo, @@ -715,7 +735,7 @@ bool AlsaPlayback::reset() for(const auto &chan : channellist) { - if(snd_pcm_hw_params_test_channels(mPcmHandle, hp, ChannelsFromDevFmt(chan, 0)) >= 0) + if(snd_pcm_hw_params_test_channels(mPcmHandle, hp.get(), ChannelsFromDevFmt(chan, 0)) >= 0) { mDevice->FmtChans = chan; mDevice->mAmbiOrder = 0; @@ -723,40 +743,42 @@ bool AlsaPlayback::reset() } } } - CHECK(snd_pcm_hw_params_set_channels(mPcmHandle, hp, mDevice->channelsFromFmt())); + CHECK(snd_pcm_hw_params_set_channels(mPcmHandle, hp.get(), mDevice->channelsFromFmt())); /* set rate (implicitly constrains period/buffer parameters) */ if(!GetConfigValueBool(mDevice->DeviceName.c_str(), "alsa", "allow-resampler", 0) || !mDevice->Flags.get()) { - if(snd_pcm_hw_params_set_rate_resample(mPcmHandle, hp, 0) < 0) + if(snd_pcm_hw_params_set_rate_resample(mPcmHandle, hp.get(), 0) < 0) ERR("Failed to disable ALSA resampler\n"); } - else if(snd_pcm_hw_params_set_rate_resample(mPcmHandle, hp, 1) < 0) + else if(snd_pcm_hw_params_set_rate_resample(mPcmHandle, hp.get(), 1) < 0) ERR("Failed to enable ALSA resampler\n"); - CHECK(snd_pcm_hw_params_set_rate_near(mPcmHandle, hp, &rate, nullptr)); + 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, &periodLen, nullptr)) < 0) + 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)); /* 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, &bufferLen, nullptr)) < 0) + 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)); /* install and prepare hardware configuration */ - CHECK(snd_pcm_hw_params(mPcmHandle, hp)); + CHECK(snd_pcm_hw_params(mPcmHandle, hp.get())); /* retrieve configuration info */ - CHECK(snd_pcm_hw_params_get_access(hp, &access)); - CHECK(snd_pcm_hw_params_get_period_size(hp, &periodSizeInFrames, nullptr)); - CHECK(snd_pcm_hw_params_get_buffer_size(hp, &bufferSizeInFrames)); - snd_pcm_hw_params_free(hp); + snd_pcm_uframes_t periodSizeInFrames{}; + snd_pcm_uframes_t bufferSizeInFrames{}; + snd_pcm_access_t access{}; + + CHECK(snd_pcm_hw_params_get_access(hp.get(), &access)); + CHECK(snd_pcm_hw_params_get_period_size(hp.get(), &periodSizeInFrames, nullptr)); + CHECK(snd_pcm_hw_params_get_buffer_size(hp.get(), &bufferSizeInFrames)); hp = nullptr; - snd_pcm_sw_params_malloc(&sp); - CHECK(snd_pcm_sw_params_current(mPcmHandle, sp)); - CHECK(snd_pcm_sw_params_set_avail_min(mPcmHandle, sp, periodSizeInFrames)); - CHECK(snd_pcm_sw_params_set_stop_threshold(mPcmHandle, sp, bufferSizeInFrames)); - CHECK(snd_pcm_sw_params(mPcmHandle, sp)); + SwParamsPtr sp{CreateSwParams()}; + CHECK(snd_pcm_sw_params_current(mPcmHandle, sp.get())); + CHECK(snd_pcm_sw_params_set_avail_min(mPcmHandle, sp.get(), periodSizeInFrames)); + CHECK(snd_pcm_sw_params_set_stop_threshold(mPcmHandle, sp.get(), bufferSizeInFrames)); + CHECK(snd_pcm_sw_params(mPcmHandle, sp.get())); #undef CHECK - snd_pcm_sw_params_free(sp); sp = nullptr; mDevice->BufferSize = static_cast(bufferSizeInFrames); @@ -766,35 +788,21 @@ bool AlsaPlayback::reset() SetDefaultChannelOrder(mDevice); return true; - -error: - ERR("%s failed: %s\n", funcerr, snd_strerror(err)); - if(hp) snd_pcm_hw_params_free(hp); - if(sp) snd_pcm_sw_params_free(sp); - return false; } bool AlsaPlayback::start() { - snd_pcm_hw_params_t *hp{}; - snd_pcm_access_t access; - const char *funcerr; - int err; - - snd_pcm_hw_params_malloc(&hp); -#define CHECK(x) if((funcerr=#x),(err=(x)) < 0) goto error - CHECK(snd_pcm_hw_params_current(mPcmHandle, hp)); + int err{}; + snd_pcm_access_t access{}; + HwParamsPtr hp{CreateHwParams()}; +#define CHECK(x) do { \ + if((err=(x)) < 0) \ + throw al::backend_exception{ALC_INVALID_VALUE, #x " failed: %s", snd_strerror(err)}; \ +} while(0) + CHECK(snd_pcm_hw_params_current(mPcmHandle, hp.get())); /* retrieve configuration info */ - CHECK(snd_pcm_hw_params_get_access(hp, &access)); + CHECK(snd_pcm_hw_params_get_access(hp.get(), &access)); #undef CHECK - if(0) - { - error: - ERR("%s failed: %s\n", funcerr, snd_strerror(err)); - if(hp) snd_pcm_hw_params_free(hp); - return false; - } - snd_pcm_hw_params_free(hp); hp = nullptr; int (AlsaPlayback::*thread_func)(){}; @@ -823,8 +831,6 @@ bool AlsaPlayback::start() catch(std::exception& e) { ERR("Could not create playback thread: %s\n", e.what()); } - catch(...) { - } mBuffer.clear(); return false; } @@ -923,72 +929,67 @@ void AlsaCapture::open(const ALCchar *name) snd_pcm_format_t format{SND_PCM_FORMAT_UNKNOWN}; switch(mDevice->FmtType) { - case DevFmtByte: - format = SND_PCM_FORMAT_S8; - break; - case DevFmtUByte: - format = SND_PCM_FORMAT_U8; - break; - case DevFmtShort: - format = SND_PCM_FORMAT_S16; - break; - case DevFmtUShort: - format = SND_PCM_FORMAT_U16; - break; - case DevFmtInt: - format = SND_PCM_FORMAT_S32; - break; - case DevFmtUInt: - format = SND_PCM_FORMAT_U32; - break; - case DevFmtFloat: - format = SND_PCM_FORMAT_FLOAT; - break; + case DevFmtByte: + format = SND_PCM_FORMAT_S8; + break; + case DevFmtUByte: + format = SND_PCM_FORMAT_U8; + break; + case DevFmtShort: + format = SND_PCM_FORMAT_S16; + break; + case DevFmtUShort: + format = SND_PCM_FORMAT_U16; + break; + case DevFmtInt: + format = SND_PCM_FORMAT_S32; + break; + case DevFmtUInt: + format = SND_PCM_FORMAT_U32; + break; + case DevFmtFloat: + format = SND_PCM_FORMAT_FLOAT; + break; } snd_pcm_uframes_t bufferSizeInFrames{maxu(mDevice->BufferSize, 100*mDevice->Frequency/1000)}; snd_pcm_uframes_t periodSizeInFrames{minu(mDevice->BufferSize, 25*mDevice->Frequency/1000)}; bool needring{false}; - const char *funcerr{}; - snd_pcm_hw_params_t *hp{}; - snd_pcm_hw_params_malloc(&hp); -#define CHECK(x) if((funcerr=#x),(err=(x)) < 0) goto error - CHECK(snd_pcm_hw_params_any(mPcmHandle, hp)); + HwParamsPtr hp{CreateHwParams()}; +#define CHECK(x) do { \ + if((err=(x)) < 0) \ + throw al::backend_exception{ALC_INVALID_VALUE, #x " failed: %s", snd_strerror(err)}; \ +} while(0) + CHECK(snd_pcm_hw_params_any(mPcmHandle, hp.get())); /* set interleaved access */ - CHECK(snd_pcm_hw_params_set_access(mPcmHandle, hp, SND_PCM_ACCESS_RW_INTERLEAVED)); + CHECK(snd_pcm_hw_params_set_access(mPcmHandle, hp.get(), SND_PCM_ACCESS_RW_INTERLEAVED)); /* set format (implicitly sets sample bits) */ - CHECK(snd_pcm_hw_params_set_format(mPcmHandle, hp, format)); + CHECK(snd_pcm_hw_params_set_format(mPcmHandle, hp.get(), format)); /* set channels (implicitly sets frame bits) */ - CHECK(snd_pcm_hw_params_set_channels(mPcmHandle, hp, mDevice->channelsFromFmt())); + CHECK(snd_pcm_hw_params_set_channels(mPcmHandle, hp.get(), mDevice->channelsFromFmt())); /* set rate (implicitly constrains period/buffer parameters) */ - CHECK(snd_pcm_hw_params_set_rate(mPcmHandle, hp, mDevice->Frequency, 0)); + CHECK(snd_pcm_hw_params_set_rate(mPcmHandle, hp.get(), mDevice->Frequency, 0)); /* set buffer size in frame units (implicitly sets period size/bytes/time and buffer time/bytes) */ - if(snd_pcm_hw_params_set_buffer_size_min(mPcmHandle, hp, &bufferSizeInFrames) < 0) + if(snd_pcm_hw_params_set_buffer_size_min(mPcmHandle, hp.get(), &bufferSizeInFrames) < 0) { TRACE("Buffer too large, using intermediate ring buffer\n"); needring = true; - CHECK(snd_pcm_hw_params_set_buffer_size_near(mPcmHandle, hp, &bufferSizeInFrames)); + CHECK(snd_pcm_hw_params_set_buffer_size_near(mPcmHandle, hp.get(), &bufferSizeInFrames)); } /* set buffer size in frame units (implicitly sets period size/bytes/time and buffer time/bytes) */ - CHECK(snd_pcm_hw_params_set_period_size_near(mPcmHandle, hp, &periodSizeInFrames, nullptr)); + CHECK(snd_pcm_hw_params_set_period_size_near(mPcmHandle, hp.get(), &periodSizeInFrames, nullptr)); /* install and prepare hardware configuration */ - CHECK(snd_pcm_hw_params(mPcmHandle, hp)); + CHECK(snd_pcm_hw_params(mPcmHandle, hp.get())); /* retrieve configuration info */ - CHECK(snd_pcm_hw_params_get_period_size(hp, &periodSizeInFrames, nullptr)); + CHECK(snd_pcm_hw_params_get_period_size(hp.get(), &periodSizeInFrames, nullptr)); #undef CHECK - snd_pcm_hw_params_free(hp); hp = nullptr; if(needring) mRing = CreateRingBuffer(mDevice->BufferSize, mDevice->frameSizeFromFmt(), false); mDevice->DeviceName = name; - return; - -error: - if(hp) snd_pcm_hw_params_free(hp); - throw al::backend_exception{ALC_INVALID_VALUE, "%s failed: %s", funcerr, snd_strerror(err)}; } @@ -996,18 +997,13 @@ bool AlsaCapture::start() { int err{snd_pcm_prepare(mPcmHandle)}; if(err < 0) - ERR("prepare failed: %s\n", snd_strerror(err)); - else - { - err = snd_pcm_start(mPcmHandle); - if(err < 0) - ERR("start failed: %s\n", snd_strerror(err)); - } + throw al::backend_exception{ALC_INVALID_VALUE, "snd_pcm_prepare failed: %s", + snd_strerror(err)}; + + err = snd_pcm_start(mPcmHandle); if(err < 0) - { - aluHandleDisconnect(mDevice, "Capture state failure: %s", snd_strerror(err)); - return false; - } + throw al::backend_exception{ALC_INVALID_VALUE, "snd_pcm_start failed: %s", + snd_strerror(err)}; mDoCapture = true; return true; -- cgit v1.2.3 From d37a294d4ce66ea3e5816042457923b72d1bc7c1 Mon Sep 17 00:00:00 2001 From: Chris Robinson Date: Sun, 27 Oct 2019 19:20:26 -0700 Subject: Add a config option for custom ALSA capture devices --- alc/backends/alsa.cpp | 34 ++++++++++++++++------------------ 1 file changed, 16 insertions(+), 18 deletions(-) (limited to 'alc/backends/alsa.cpp') diff --git a/alc/backends/alsa.cpp b/alc/backends/alsa.cpp index 1b8c6298..7dc3c3c4 100644 --- a/alc/backends/alsa.cpp +++ b/alc/backends/alsa.cpp @@ -267,27 +267,25 @@ al::vector probe_devices(snd_pcm_stream_t stream) GetConfigValue(nullptr, "alsa", (stream==SND_PCM_STREAM_PLAYBACK) ? "device" : "capture", "default")}); - if(stream == SND_PCM_STREAM_PLAYBACK) + const char *customdevs{GetConfigValue(nullptr, "alsa", + (stream == SND_PCM_STREAM_PLAYBACK) ? "custom-devices" : "custom-captures", "")}; + while(const char *curdev{customdevs}) { - const char *customdevs; - const char *next{GetConfigValue(nullptr, "alsa", "custom-devices", "")}; - while((customdevs=next) != nullptr && customdevs[0]) + if(!curdev[0]) break; + customdevs = strchr(curdev, ';'); + const char *sep{strchr(curdev, '=')}; + if(!sep) { - next = strchr(customdevs, ';'); - const char *sep{strchr(customdevs, '=')}; - if(!sep) - { - std::string spec{next ? std::string(customdevs, next++) : std::string(customdevs)}; - ERR("Invalid ALSA device specification \"%s\"\n", spec.c_str()); - continue; - } - - const char *oldsep{sep++}; - devlist.emplace_back(DevMap{std::string(customdevs, oldsep), - next ? std::string(sep, next++) : std::string(sep)}); - const auto &entry = devlist.back(); - TRACE("Got device \"%s\", \"%s\"\n", entry.name.c_str(), entry.device_name.c_str()); + std::string spec{customdevs ? std::string(curdev, customdevs++) : std::string(curdev)}; + ERR("Invalid ALSA device specification \"%s\"\n", spec.c_str()); + continue; } + + const char *oldsep{sep++}; + devlist.emplace_back(DevMap{std::string(curdev, oldsep), + customdevs ? std::string(sep, customdevs++) : std::string(sep)}); + const auto &entry = devlist.back(); + TRACE("Got device \"%s\", \"%s\"\n", entry.name.c_str(), entry.device_name.c_str()); } const std::string main_prefix{ -- cgit v1.2.3