Merge pull request 'Bounded PCM playback with owned samples and voice lifetimes (#18)' (#34) from issue/18-windows-pcm-playback into main

This commit was merged in pull request #34.
This commit is contained in:
faumaray committed 2026-12-03 08:08:41 +00:00
commit f6002c1996
2 files changed
+532

No files matched your search

+406
View File
@@ -0,0 +1,406 @@
#pragma once
#include <Void/System/Types.hpp>
#include <chrono>
#include <cstdint>
#include <expected>
#include <memory>
#include <mutex>
#include <string>
#include <unordered_map>
#include <utility>
#include <vector>
#ifdef _WIN32
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <mmsystem.h>
#include <windows.h>
#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<PcmSample> 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<std::int64_t>(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<AudioDevice, AudioError>
open(AudioLimits limits = {})
{
auto impl = std::make_unique<Impl>();
impl->limits = limits;
#ifdef _WIN32
impl->silent = false;
#else
impl->silent = true;
#endif
return AudioDevice{std::move(impl)};
}
static std::expected<AudioDevice, AudioError>
open_silent(AudioLimits limits = {})
{
auto impl = std::make_unique<Impl>();
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<VoiceId, AudioError>
play(std::shared_ptr<const PcmBuffer> 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<const PcmBuffer> 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<VoiceId, Voice> voices;
VoiceId next_id{1};
bool silent{true};
bool available{true};
bool closed{false};
};
explicit AudioDevice(std::unique_ptr<Impl> 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<void, AudioError> start_win32(Voice& voice)
{
voice.format.wFormatTag = WAVE_FORMAT_PCM;
voice.format.nChannels =
static_cast<WORD>(voice.buffer->format.channels);
voice.format.nSamplesPerSec =
static_cast<DWORD>(voice.buffer->format.sample_rate);
voice.format.wBitsPerSample = 16;
voice.format.nBlockAlign =
static_cast<WORD>(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<LPSTR>(
const_cast<PcmSample*>(voice.buffer->samples.data()));
voice.header.dwBufferLength = static_cast<DWORD>(
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> impl_;
};
} // namespace Void::System