From df2ed107e2b848096986771cad056279a6a28f19 Mon Sep 17 00:00:00 2001 From: Aleksey Selihov <1+faumaray@noreply@void.com> Date: Thu, 3 Dec 2026 07:03:05 +0000 Subject: [PATCH 1/2] feat(System): bounded PCM playback with owned samples and voice lifetimes (#18) --- include/Void/System/Audio.hpp | 406 ++++++++++++++++++++++++++++++++++ 1 file changed, 406 insertions(+) create mode 100644 include/Void/System/Audio.hpp diff --git a/include/Void/System/Audio.hpp b/include/Void/System/Audio.hpp new file mode 100644 index 0000000..ae50c80 --- /dev/null +++ b/include/Void/System/Audio.hpp @@ -0,0 +1,406 @@ +#pragma once + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef _WIN32 +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include +#include +#endif + +namespace Void::System +{ + +using PcmSample = std::int16_t; + +struct PcmFormat { + std::uint32_t sample_rate{44100}; + std::uint16_t channels{2}; + + [[nodiscard]] bool operator==(const PcmFormat&) const noexcept = default; +}; + +/// Owned PCM sample data. The device keeps it alive for as long as a voice +/// references it; callers may release their handle right after submission. +struct PcmBuffer { + PcmFormat format; + std::vector samples; + + [[nodiscard]] std::chrono::microseconds duration() const noexcept + { + const std::uint64_t frames = + format.channels == 0 + ? 0 + : samples.size() / format.channels; + if (format.sample_rate == 0) { + return std::chrono::microseconds{0}; + } + return std::chrono::microseconds{ + static_cast(frames) * 1'000'000 / + format.sample_rate}; + } +}; + +enum class AudioStatus : std::uint8_t { + ok = 0, + /// No output device is available; the caller can continue silently. + device_unavailable, + voice_limit, + invalid_buffer, + backend_error, + closed, +}; + +struct AudioError { + AudioStatus status{AudioStatus::backend_error}; + std::string message; + + [[nodiscard]] bool operator==(const AudioError&) const = default; +}; + +enum class VoiceState : std::uint8_t { + playing = 0, + stopped, + finished, + unknown, +}; + +using VoiceId = std::uint64_t; + +struct AudioLimits { + std::size_t max_voices{8}; +}; + +/// Bounded PCM playback with owned samples and explicit voice lifetimes. +/// +/// `play` transfers a shared handle to the device; the caller may drop its +/// handle immediately and the samples stay alive until the voice is stopped, +/// finishes or the device closes. `stop` ends a voice (including a loop), +/// `state` reports and reaps finished voices, and the destructor tears every +/// voice down. A missing device is reported as `device_unavailable` so an +/// application can continue without audio; `open_silent` provides the same +/// lifetime semantics without a device (used for tests and headless runs). +/// +/// Thread-safe. +class AudioDevice +{ + public: + + static std::expected + open(AudioLimits limits = {}) + { + auto impl = std::make_unique(); + impl->limits = limits; +#ifdef _WIN32 + impl->silent = false; +#else + impl->silent = true; +#endif + return AudioDevice{std::move(impl)}; + } + + static std::expected + open_silent(AudioLimits limits = {}) + { + auto impl = std::make_unique(); + impl->limits = limits; + impl->silent = true; + return AudioDevice{std::move(impl)}; + } + + AudioDevice(AudioDevice&&) noexcept = default; + AudioDevice& operator=(AudioDevice&&) noexcept = default; + + AudioDevice(const AudioDevice&) = delete; + AudioDevice& operator=(const AudioDevice&) = delete; + + ~AudioDevice() { close(); } + + [[nodiscard]] bool available() const + { + std::lock_guard lock{impl_->mutex}; + return !impl_->closed && impl_->available; + } + + /// Submit owned samples. On success the device owns a reference; on + /// failure the caller's handle is untouched. + [[nodiscard]] std::expected + play(std::shared_ptr buffer, bool loop = false) + { + Impl& impl = *impl_; + std::lock_guard lock{impl.mutex}; + reap(impl); + if (impl.closed) { + return std::unexpected{ + AudioError{AudioStatus::closed, "audio device is closed"}}; + } + if (!impl.available) { + return std::unexpected{AudioError{ + AudioStatus::device_unavailable, + "no audio output device"}}; + } + if (buffer == nullptr || buffer->format.channels == 0 || + buffer->samples.empty()) { + return std::unexpected{AudioError{ + AudioStatus::invalid_buffer, "empty PCM buffer"}}; + } + if (impl.voices.size() >= impl.limits.max_voices) { + return std::unexpected{AudioError{ + AudioStatus::voice_limit, "voice limit reached"}}; + } + + Voice voice; + voice.id = impl.next_id++; + voice.buffer = std::move(buffer); + voice.loop = loop; + voice.state = VoiceState::playing; + voice.started = std::chrono::steady_clock::now(); +#ifdef _WIN32 + if (!impl.silent) { + if (const auto error = start_win32(voice); !error.has_value()) { + return std::unexpected{error.error()}; + } + } +#endif + const VoiceId id = voice.id; + impl.voices.emplace(id, std::move(voice)); + return id; + } + + /// Stop a voice (including a loop) and release its samples. + bool stop(VoiceId id) + { + Impl& impl = *impl_; + std::lock_guard lock{impl.mutex}; + const auto found = impl.voices.find(id); + if (found == impl.voices.end()) { + return false; + } + found->second.state = VoiceState::stopped; + release(impl, found->second); + impl.voices.erase(found); + return true; + } + + /// Current state; finished voices are reaped and their samples + /// released. + [[nodiscard]] VoiceState state(VoiceId id) + { + Impl& impl = *impl_; + std::lock_guard lock{impl.mutex}; + const auto found = impl.voices.find(id); + if (found == impl.voices.end()) { + return VoiceState::unknown; + } + Voice& voice = found->second; +#ifdef _WIN32 + if (!impl.silent) { + service_win32(voice); + } +#endif + if (voice.state == VoiceState::playing && !voice.loop && + std::chrono::steady_clock::now() - voice.started >= + voice.buffer->duration()) { + voice.state = VoiceState::finished; + } + const VoiceState result = voice.state; + if (result == VoiceState::finished || + result == VoiceState::stopped) { + release(impl, voice); + impl.voices.erase(found); + } + return result; + } + + [[nodiscard]] std::size_t active_voices() + { + Impl& impl = *impl_; + std::lock_guard lock{impl.mutex}; + reap(impl); + return impl.voices.size(); + } + + void close() + { + if (impl_ == nullptr) { + return; + } + Impl& impl = *impl_; + std::lock_guard lock{impl.mutex}; + for (auto& [id, voice] : impl.voices) { + (void)id; + stop_backend(voice); + voice.buffer.reset(); + } + impl.voices.clear(); + impl.closed = true; + } + + private: + + struct Voice { + VoiceId id{0}; + std::shared_ptr buffer; + bool loop{false}; + VoiceState state{VoiceState::playing}; + std::chrono::steady_clock::time_point started{}; +#ifdef _WIN32 + HWAVEOUT wave{}; + WAVEHDR header{}; + WAVEFORMATEX format{}; + bool prepared{false}; +#endif + }; + + struct Impl { + mutable std::mutex mutex; + AudioLimits limits{}; + std::unordered_map voices; + VoiceId next_id{1}; + bool silent{true}; + bool available{true}; + bool closed{false}; + }; + + explicit AudioDevice(std::unique_ptr impl) + : impl_(std::move(impl)) + { + } + + static void release(Impl& impl, Voice& voice) + { + (void)impl; +#ifdef _WIN32 + stop_backend(voice); +#endif + voice.buffer.reset(); + } + + /// Reap voices that finished. Silent non-loop voices finish after + /// their duration; looping voices stay until stopped. + static void reap(Impl& impl) + { + const auto now = std::chrono::steady_clock::now(); + for (auto iterator = impl.voices.begin(); + iterator != impl.voices.end();) { + Voice& voice = iterator->second; +#ifdef _WIN32 + if (!impl.silent) { + service_win32(voice); + } +#endif + if (voice.state == VoiceState::playing && !voice.loop && + now - voice.started >= voice.buffer->duration()) { + voice.state = VoiceState::finished; + } + if (voice.state == VoiceState::finished || + voice.state == VoiceState::stopped) { + release(impl, voice); + iterator = impl.voices.erase(iterator); + } else { + ++iterator; + } + } + } + +#ifdef _WIN32 + static std::expected start_win32(Voice& voice) + { + voice.format.wFormatTag = WAVE_FORMAT_PCM; + voice.format.nChannels = + static_cast(voice.buffer->format.channels); + voice.format.nSamplesPerSec = + static_cast(voice.buffer->format.sample_rate); + voice.format.wBitsPerSample = 16; + voice.format.nBlockAlign = + static_cast(voice.format.nChannels * 2); + voice.format.nAvgBytesPerSec = + voice.format.nSamplesPerSec * voice.format.nBlockAlign; + voice.format.cbSize = 0; + + const MMRESULT opened = ::waveOutOpen( + &voice.wave, WAVE_MAPPER, &voice.format, 0, 0, + CALLBACK_NULL); + if (opened != MMSYSERR_NOERROR) { + voice.wave = nullptr; + return std::unexpected{AudioError{ + AudioStatus::device_unavailable, + "waveOutOpen failed"}}; + } + voice.header = WAVEHDR{}; + voice.header.lpData = + reinterpret_cast( + const_cast(voice.buffer->samples.data())); + voice.header.dwBufferLength = static_cast( + voice.buffer->samples.size() * sizeof(PcmSample)); + if (::waveOutPrepareHeader(voice.wave, &voice.header, + sizeof(WAVEHDR)) != + MMSYSERR_NOERROR) { + ::waveOutClose(voice.wave); + voice.wave = nullptr; + return std::unexpected{AudioError{ + AudioStatus::backend_error, + "waveOutPrepareHeader failed"}}; + } + voice.prepared = true; + if (::waveOutWrite(voice.wave, &voice.header, sizeof(WAVEHDR)) != + MMSYSERR_NOERROR) { + stop_backend(voice); + return std::unexpected{AudioError{ + AudioStatus::backend_error, "waveOutWrite failed"}}; + } + return {}; + } + + static void service_win32(Voice& voice) + { + if (voice.wave == nullptr || + (voice.header.dwFlags & WHDR_DONE) == 0) { + return; + } + if (voice.loop) { + // Re-queue the same prepared header for another pass. + voice.header.dwFlags &= ~WHDR_DONE; + (void)::waveOutWrite(voice.wave, &voice.header, + sizeof(WAVEHDR)); + } else { + voice.state = VoiceState::finished; + } + } + + static void stop_backend(Voice& voice) + { + if (voice.wave != nullptr) { + (void)::waveOutReset(voice.wave); + if (voice.prepared) { + (void)::waveOutUnprepareHeader( + voice.wave, &voice.header, sizeof(WAVEHDR)); + voice.prepared = false; + } + (void)::waveOutClose(voice.wave); + voice.wave = nullptr; + } + } +#else + static void stop_backend(Voice&) {} +#endif + + std::unique_ptr impl_; +}; + +} // namespace Void::System From caebb7f7f112e8599e34d7f133d6ffee6dc6f679 Mon Sep 17 00:00:00 2001 From: Aleksey Selihov <1+faumaray@noreply@void.com> Date: Thu, 3 Dec 2026 07:03:09 +0000 Subject: [PATCH 2/2] feat(System): bounded PCM playback with owned samples and voice lifetimes (#18) --- tests/standalone/System/Audio.cpp | 126 ++++++++++++++++++++++++++++++ 1 file changed, 126 insertions(+) create mode 100644 tests/standalone/System/Audio.cpp diff --git a/tests/standalone/System/Audio.cpp b/tests/standalone/System/Audio.cpp new file mode 100644 index 0000000..be6bb16 --- /dev/null +++ b/tests/standalone/System/Audio.cpp @@ -0,0 +1,126 @@ +#include +#include +#include + +#include +#include +#include + +namespace +{ + +using Void::System::AudioDevice; +using Void::System::AudioStatus; +using Void::System::PcmBuffer; +using Void::System::VoiceState; + +[[nodiscard]] std::shared_ptr + buffer(std::uint32_t rate = 44100, std::uint16_t channels = 1, + std::size_t frames = 4) +{ + PcmBuffer value; + value.format = {.sample_rate = rate, .channels = channels}; + value.samples.assign(frames * channels, 100); + return std::make_shared(std::move(value)); +} + +} // namespace + +Void::Testing::Test audio_play_owns_samples_and_stop_releases() +{ + auto device = AudioDevice::open_silent(); + Void::Testing::require(device.has_value()); + + auto samples = buffer(); + std::weak_ptr weak = samples; + auto voice = device->play(samples, /*loop=*/true); + Void::Testing::require(voice.has_value()); + samples.reset(); + Void::Testing::expect(!weak.expired()); + + Void::Testing::expect(device->stop(*voice)); + Void::Testing::expect(weak.expired()); + Void::Testing::expect_eq(device->active_voices(), std::size_t{0}); +} + +Void::Testing::Test audio_voice_cap() +{ + auto device = AudioDevice::open_silent({.max_voices = 2}); + Void::Testing::require(device.has_value()); + + auto first = device->play(buffer(), true); + auto second = device->play(buffer(), true); + Void::Testing::require(first.has_value() && second.has_value()); + auto third = device->play(buffer(), true); + Void::Testing::require(!third.has_value()); + Void::Testing::expect(third.error().status == AudioStatus::voice_limit); + + Void::Testing::expect(device->stop(*first)); + auto reused = device->play(buffer(), true); + Void::Testing::expect(reused.has_value()); +} + +Void::Testing::Test audio_loop_stays_until_stopped() +{ + auto device = AudioDevice::open_silent(); + Void::Testing::require(device.has_value()); + auto voice = device->play(buffer(), true); + Void::Testing::require(voice.has_value()); + Void::Testing::expect(device->state(*voice) == VoiceState::playing); + Void::Testing::expect(device->stop(*voice)); + Void::Testing::expect(device->state(*voice) == VoiceState::unknown); +} + +Void::Testing::Test audio_non_loop_finishes_and_releases() +{ + auto device = AudioDevice::open_silent(); + Void::Testing::require(device.has_value()); + // A zero-length duration finishes on the next state query. + auto samples = buffer(1'000'000'000, 1, 1); + std::weak_ptr weak = samples; + auto voice = device->play(samples, /*loop=*/false); + Void::Testing::require(voice.has_value()); + samples.reset(); + Void::Testing::expect(device->state(*voice) == VoiceState::finished); + Void::Testing::expect(weak.expired()); +} + +Void::Testing::Test audio_close_stops_active_voices_and_reopens() +{ + auto device = AudioDevice::open_silent(); + Void::Testing::require(device.has_value()); + auto samples = buffer(); + std::weak_ptr weak = samples; + auto voice = device->play(samples, true); + Void::Testing::require(voice.has_value()); + samples.reset(); + + device->close(); + Void::Testing::expect(weak.expired()); + Void::Testing::expect_eq(device->active_voices(), std::size_t{0}); + auto rejected = device->play(buffer(), true); + Void::Testing::require(!rejected.has_value()); + Void::Testing::expect(rejected.error().status == AudioStatus::closed); + + auto reopened = AudioDevice::open_silent(); + Void::Testing::require(reopened.has_value()); + Void::Testing::expect(reopened->play(buffer(), true).has_value()); +} + +Void::Testing::Test audio_rejects_invalid_buffers() +{ + auto device = AudioDevice::open_silent(); + Void::Testing::require(device.has_value()); + auto null_buffer = device->play(nullptr); + Void::Testing::require(!null_buffer.has_value()); + Void::Testing::expect(null_buffer.error().status == + AudioStatus::invalid_buffer); + + PcmBuffer empty; + empty.format = {.sample_rate = 44100, .channels = 1}; + auto empty_buffer = device->play( + std::make_shared(std::move(empty))); + Void::Testing::require(!empty_buffer.has_value()); + Void::Testing::expect(empty_buffer.error().status == + AudioStatus::invalid_buffer); +}