psemek/libs/audio/source/mixer.cpp

106 lines
1.9 KiB
C++

#include <psemek/audio/mixer.hpp>
#include <memory>
#include <vector>
#include <atomic>
#include <mutex>
namespace psemek::audio
{
namespace
{
struct mixer_impl final
: mixer
, std::enable_shared_from_this<mixer_impl>
{
channel_ptr add(stream_ptr stream) override;
std::size_t read(util::span<float> samples) override;
std::optional<std::size_t> length() const override
{
return std::nullopt;
}
std::size_t played() const override
{
return played_.load();
}
private:
std::vector<channel_ptr> channels_;
std::vector<channel_ptr> alive_channels_;
std::vector<float> buffer_;
std::mutex new_channels_mutex_;
std::vector<channel_ptr> new_channels_;
std::atomic<std::size_t> played_{0};
};
channel_ptr mixer_impl::add(stream_ptr stream)
{
auto result = std::make_shared<channel>(std::move(stream));
{
std::lock_guard lock{new_channels_mutex_};
new_channels_.push_back(result);
}
return result;
}
std::size_t mixer_impl::read(util::span<float> samples)
{
{
std::vector<channel_ptr> new_channels;
{
std::lock_guard lock{new_channels_mutex_};
new_channels = std::move(new_channels_);
}
for (auto & ch : new_channels)
channels_.push_back(std::move(ch));
}
std::fill(samples.begin(), samples.end(), 0.f);
buffer_.resize(samples.size());
for (auto & ch : channels_)
{
auto stream = ch->stream();
if (!stream)
continue;
auto read = stream->read(buffer_);
std::copy(buffer_.data(), buffer_.data() + read, samples.begin());
if (read < buffer_.size())
{
ch->stop();
continue;
}
alive_channels_.push_back(std::move(ch));
}
std::swap(channels_, alive_channels_);
alive_channels_.clear();
played_.fetch_add(samples.size());
return samples.size();
}
}
mixer_ptr make_mixer()
{
return std::make_shared<mixer_impl>();
}
}