From 0370c64f9909af53167b2c8c3ec088399f442992 Mon Sep 17 00:00:00 2001 From: Robbert van der Helm Date: Thu, 10 Jun 2021 14:13:18 +0200 Subject: [PATCH] Allow resizing shared memory buffers --- src/common/audio-shm.cpp | 23 +++++++++++++++++++++++ src/common/audio-shm.h | 19 +++++++++++++++---- 2 files changed, 38 insertions(+), 4 deletions(-) diff --git a/src/common/audio-shm.cpp b/src/common/audio-shm.cpp index a2d7d3bc..99dafd43 100644 --- a/src/common/audio-shm.cpp +++ b/src/common/audio-shm.cpp @@ -36,9 +36,32 @@ AudioShmBuffer::~AudioShmBuffer() noexcept { } } +void AudioShmBuffer::resize(const Config& new_config) { + if (new_config.name != config.name) { + throw std::invalid_argument("Expected buffer configuration for \"" + + config.name + "\", got \"" + + new_config.name + "\""); + } + + config = new_config; + shm.truncate(config.size); + buffer = + boost::interprocess::mapped_region(shm, boost::interprocess::read_write, + 0, config.size, nullptr, MAP_LOCKED); +} + AudioShmBuffer::AudioShmBuffer(AudioShmBuffer&& o) noexcept : config(std::move(o.config)), shm(std::move(o.shm)), buffer(std::move(o.buffer)) { o.is_moved = true; } + +AudioShmBuffer& AudioShmBuffer::operator=(AudioShmBuffer&& o) noexcept { + config = std::move(o.config); + shm = std::move(o.shm); + buffer = std::move(o.buffer); + o.is_moved = true; + + return *this; +} diff --git a/src/common/audio-shm.h b/src/common/audio-shm.h index 74f2bc1d..cc8a3ee0 100644 --- a/src/common/audio-shm.h +++ b/src/common/audio-shm.h @@ -121,11 +121,21 @@ class AudioShmBuffer { AudioShmBuffer& operator=(const AudioShmBuffer&) = delete; AudioShmBuffer(AudioShmBuffer&&) noexcept; - AudioShmBuffer& operator=(AudioShmBuffer&&) = delete; + AudioShmBuffer& operator=(AudioShmBuffer&&) noexcept; + + /** + * Adapt to a new buffer size or channel layout. The name of the buffer + * needs to remain the same. + * + * @throw `std::invalid_argument` If the config is for a buffer with a + * different name. + */ + void resize(const Config& new_config); /** * Get a pointer to the part of the buffer where this input audio channel is - * stored in. Both the bus and the channel indices start at zero. + * stored in. Both the bus and the channel indices start at zero. These + * addresses might change after a call to `resize()`. */ template T* input_channel_ptr(const uint32_t bus, const uint32_t channel) { @@ -135,7 +145,8 @@ class AudioShmBuffer { /** * Get a pointer to the part of the buffer where this output audio channel - * is stored in. Both the bus and the channel indices start at zero. + * is stored in. Both the bus and the channel indices start at zero. These + * addresses might change after a call to `resize()`. */ template T* output_channel_ptr(const uint32_t bus, const uint32_t channel) { @@ -143,7 +154,7 @@ class AudioShmBuffer { config.output_offsets[bus][channel]; } - const Config config; + Config config; private: boost::interprocess::shared_memory_object shm;