Add audio stream duplication

This commit is contained in:
Nikita Lisitsa 2022-10-05 20:57:09 +03:00
parent 65f71e54a8
commit d346f7b50d
2 changed files with 70 additions and 0 deletions

View file

@ -0,0 +1,12 @@
#pragma once
#include <psemek/audio/stream.hpp>
#include <utility>
namespace psemek::audio
{
std::pair<stream_ptr, stream_ptr> duplicate(stream_ptr stream);
}

View file

@ -0,0 +1,58 @@
#include <psemek/audio/duplicate.hpp>
#include <vector>
namespace psemek::audio
{
namespace
{
struct duplicate_common
{
duplicate_common(stream_ptr stream)
: stream(std::move(stream))
{}
stream_ptr stream;
std::vector<float> buffer;
std::size_t counter = 0;
std::size_t read = 0;
};
struct duplicate_impl
: stream
{
duplicate_impl(std::shared_ptr<duplicate_common> common)
: common_(std::move(common))
{}
std::size_t read(float * data, std::size_t sample_count) override
{
if (counter_ == common_->counter)
{
++common_->counter;
if (common_->buffer.size() < sample_count)
common_->buffer.resize(sample_count);
common_->read = common_->stream->read(common_->buffer.data(), sample_count);
}
std::copy(common_->buffer.data(), common_->buffer.data() + common_->read, data);
++counter_;
return common_->read;
}
private:
std::shared_ptr<duplicate_common> common_;
std::size_t counter_ = 0;
};
}
std::pair<stream_ptr, stream_ptr> duplicate(stream_ptr stream)
{
auto common = std::make_shared<duplicate_common>(std::move(stream));
return {std::make_shared<duplicate_impl>(common), std::make_shared<duplicate_impl>(common)};
}
}