Files
EchoionApi/include/echoion/api/MemoryPool.hpp
T
2026-02-01 23:05:41 +03:00

288 lines
7.5 KiB
C++

#pragma once
#include "Types.hpp"
#include <vector>
#include <memory>
#include <mutex>
#include <queue>
#include <atomic>
#include <cstring>
namespace Echoion::Api {
// Custom allocator for audio buffers
template<typename T>
class MemoryPool {
public:
explicit MemoryPool(size_t blockSize, size_t initialBlocks = 64)
: blockSize_(blockSize)
, capacity_(initialBlocks) {
// Pre-allocate memory
storage_.resize(blockSize_ * capacity_);
// Initialize free list
for (size_t i = 0; i < capacity_; ++i) {
freeList_.push(&storage_[i * blockSize_]);
}
available_.store(capacity_, std::memory_order_relaxed);
}
~MemoryPool() = default;
// Non-copyable, non-movable
MemoryPool(const MemoryPool&) = delete;
MemoryPool& operator=(const MemoryPool&) = delete;
MemoryPool(MemoryPool&&) = delete;
MemoryPool& operator=(MemoryPool&&) = delete;
// Allocate a block
[[nodiscard]] T* acquire() {
std::lock_guard<std::mutex> lock(mutex_);
if (freeList_.empty()) {
// Grow pool if needed
grow();
}
if (freeList_.empty()) {
return nullptr; // Out of memory
}
T* block = freeList_.front();
freeList_.pop();
available_.fetch_sub(1, std::memory_order_relaxed);
return block;
}
// Release a block back to pool
void release(T* block) {
if (!block) return;
// Verify block belongs to this pool
if (!contains(block)) {
return; // Or assert/panic
}
std::lock_guard<std::mutex> lock(mutex_);
freeList_.push(block);
available_.fetch_add(1, std::memory_order_relaxed);
}
// Get available blocks count
[[nodiscard]] size_t available() const {
return available_.load(std::memory_order_relaxed);
}
// Get total capacity
[[nodiscard]] size_t capacity() const {
std::lock_guard<std::mutex> lock(mutex_);
return capacity_;
}
// Get block size
[[nodiscard]] size_t blockSize() const {
return blockSize_;
}
// Reserve additional blocks
void reserve(size_t additionalBlocks) {
std::lock_guard<std::mutex> lock(mutex_);
size_t oldCapacity = capacity_;
size_t newCapacity = capacity_ + additionalBlocks;
storage_.resize(blockSize_ * newCapacity);
// Add new blocks to free list
for (size_t i = oldCapacity; i < newCapacity; ++i) {
freeList_.push(&storage_[i * blockSize_]);
}
capacity_ = newCapacity;
available_.fetch_add(additionalBlocks, std::memory_order_relaxed);
}
private:
[[nodiscard]] bool contains(const T* block) const {
return block >= &storage_[0] &&
block <= &storage_[(capacity_ - 1) * blockSize_];
}
void grow() {
// Double the capacity
size_t additionalBlocks = capacity_;
reserve(additionalBlocks);
}
size_t blockSize_;
size_t capacity_;
std::vector<T> storage_;
std::queue<T*> freeList_;
mutable std::mutex mutex_;
std::atomic<size_t> available_;
};
// Smart pointer for pooled memory
template<typename T>
class PooledPtr {
public:
PooledPtr() = default;
PooledPtr(T* ptr, MemoryPool<T>* pool)
: ptr_(ptr), pool_(pool) {}
~PooledPtr() {
reset();
}
// Move semantics only
PooledPtr(PooledPtr&& other) noexcept
: ptr_(other.ptr_), pool_(other.pool_) {
other.ptr_ = nullptr;
other.pool_ = nullptr;
}
PooledPtr& operator=(PooledPtr&& other) noexcept {
if (this != &other) {
reset();
ptr_ = other.ptr_;
pool_ = other.pool_;
other.ptr_ = nullptr;
other.pool_ = nullptr;
}
return *this;
}
// Delete copy
PooledPtr(const PooledPtr&) = delete;
PooledPtr& operator=(const PooledPtr&) = delete;
[[nodiscard]] T* get() const { return ptr_; }
[[nodiscard]] T& operator*() const { return *ptr_; }
[[nodiscard]] T* operator->() const { return ptr_; }
[[nodiscard]] explicit operator bool() const { return ptr_ != nullptr; }
[[nodiscard]] T* release() {
T* tmp = ptr_;
ptr_ = nullptr;
pool_ = nullptr;
return tmp;
}
void reset() {
if (ptr_ && pool_) {
pool_->release(ptr_);
}
ptr_ = nullptr;
pool_ = nullptr;
}
private:
T* ptr_ = nullptr;
MemoryPool<T>* pool_ = nullptr;
};
// Specialized audio buffer pool
class AudioBufferPool {
public:
static constexpr size_t DEFAULT_BUFFER_SIZE = 1920; // 48000Hz * 2ch * 20ms
static constexpr size_t DEFAULT_POOL_SIZE = 256; // ~7.5MB for float buffers
static AudioBufferPool& instance();
void initialize(size_t bufferSize = DEFAULT_BUFFER_SIZE,
size_t poolSize = DEFAULT_POOL_SIZE);
void shutdown();
// Get a buffer (returns nullptr if pool exhausted)
[[nodiscard]] PooledPtr<float> acquireBuffer();
// Get buffer size
[[nodiscard]] size_t getBufferSize() const { return bufferSize_; }
// Get stats
[[nodiscard]] size_t getAvailableBuffers() const;
[[nodiscard]] size_t getTotalBuffers() const;
private:
AudioBufferPool() = default;
std::unique_ptr<MemoryPool<float>> pool_;
size_t bufferSize_ = DEFAULT_BUFFER_SIZE;
};
// Zero-copy audio buffer view
template<typename T>
class AudioBufferView {
public:
AudioBufferView() = default;
AudioBufferView(T* data, size_t size, size_t channels = 2)
: data_(data), size_(size), channels_(channels) {}
[[nodiscard]] T* data() { return data_; }
[[nodiscard]] const T* data() const { return data_; }
[[nodiscard]] size_t size() const { return size_; }
[[nodiscard]] size_t channels() const { return channels_; }
[[nodiscard]] size_t samplesPerChannel() const { return size_ / channels_; }
[[nodiscard]] T* channel(size_t ch) {
return data_ + ch;
}
[[nodiscard]] T& sample(size_t frame, size_t ch) {
return data_[frame * channels_ + ch];
}
[[nodiscard]] const T& sample(size_t frame, size_t ch) const {
return data_[frame * channels_ + ch];
}
// Span for single channel
[[nodiscard]] std::span<T> getChannelSpan(size_t ch) {
return std::span<T>(data_ + ch, size_, channels_);
}
// Span for all data
[[nodiscard]] std::span<T> getSpan() {
return std::span<T>(data_, size_);
}
[[nodiscard]] bool empty() const { return data_ == nullptr || size_ == 0; }
void clear() {
if (data_) {
std::memset(data_, 0, size_ * sizeof(T));
}
}
// Apply gain in-place
void applyGain(float gain) {
if (!data_) return;
for (size_t i = 0; i < size_; ++i) {
data_[i] *= gain;
}
}
// Mix another buffer into this one
void mix(const AudioBufferView& other, float gain = 1.0f) {
if (!data_ || !other.data_) return;
size_t mixSize = std::min(size_, other.size_);
for (size_t i = 0; i < mixSize; ++i) {
data_[i] += other.data_[i] * gain;
}
}
private:
T* data_ = nullptr;
size_t size_ = 0;
size_t channels_ = 2;
};
using FloatAudioView = AudioBufferView<float>;
} // namespace Echoion::Api