From 716f21bc109113329256b56a759f713d11f1eb2d Mon Sep 17 00:00:00 2001 From: Sam Hocevar Date: Fri, 16 Feb 2024 01:04:54 +0100 Subject: [PATCH] audio: add clamping to mixer class --- include/lol/private/audio/stream.h | 33 ++++++++++++++++++++++-------- 1 file changed, 24 insertions(+), 9 deletions(-) diff --git a/include/lol/private/audio/stream.h b/include/lol/private/audio/stream.h index 73791b9c..c5be9443 100644 --- a/include/lol/private/audio/stream.h +++ b/include/lol/private/audio/stream.h @@ -81,31 +81,46 @@ public: void add(std::shared_ptr> s) { // FIXME: check the channel count! - m_streamers.insert(s); + m_streams.insert(s); } void remove(std::shared_ptr> s) { - m_streamers.erase(s); + m_streams.erase(s); } virtual size_t get(T *buf, size_t frames) override { - memset(buf, 0, frames * this->frame_size()); + std::vector> buffers; + size_t const samples = frames * this->channels(); - std::vector tmp(frames * this->channels()); - for (auto s : m_streamers) + for (auto s : m_streams) { - s->get(tmp.data(), frames); - for (size_t i = 0; i < tmp.size(); ++i) - buf[i] += tmp[i]; + buffers.push_back(std::vector(samples)); + s->get(buffers.back().data(), frames); + } + + for (size_t n = 0; n < samples; ++n) + { + T sample = T(0); + for (auto const &b : buffers) + sample += b[n]; + + if constexpr (std::is_same_v) + buf[n] = std::min(1.0f, std::max(-1.0f, sample)); + else if constexpr (std::is_same_v) + buf[n] = std::min(int16_t(32767), std::max(int16_t(-32768), sample)); + else if constexpr (std::is_same_v) + buf[n] = std::min(uint16_t(65535), std::max(uint16_t(0), sample)); + else + buf[n] = sample; } return frames; } protected: - std::unordered_set>> m_streamers; + std::unordered_set>> m_streams; }; template