#include "backends/wasapi_exclusive_pcm_backend.h"

#include <algorithm>
#include <atomic>
#include <chrono>
#include <cmath>
#include <cstring>
#include <limits>
#include <mutex>
#include <sstream>
#include <thread>
#include <utility>
#include <vector>

#include "backends/audio_thread_scheduling.h"
#include "backends/wasapi_endpoint_discovery.h"
#include "backends/wasapi_error.h"
#include "backends/wasapi_format_probe.h"
#include "core/dop_generator.h"
#include "core/high_load_diagnostics.h"
#include "core/pcm_sample_conversion.h"
#include "core/signal_generator.h"

#if defined(_WIN32)
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <windows.h>
#include <audioclient.h>
#include <mmdeviceapi.h>
#include <mmreg.h>
#endif

namespace aptt {
namespace {

constexpr int kWasapiInvalidArgument = 0x70057;
constexpr int kWasapiNotInitialized = 0x21001;
constexpr int kWasapiInvalidState = 0x21002;
constexpr int kWasapiResetDisabled = 0x21003;
constexpr int kWasapiNotImplemented =
    static_cast<int>(static_cast<std::int32_t>(0x80004001u));
constexpr std::uint64_t kHundredNsPerMs = 10000;
constexpr std::uint64_t kHundredNsPerSecond = 10000000;

#if defined(_WIN32)

constexpr CLSID kClsidMmDeviceEnumerator = {
    0xbcde0395,
    0xe52f,
    0x467c,
    {0x8e, 0x3d, 0xc4, 0x57, 0x92, 0x91, 0x69, 0x2e},
};

constexpr GUID kWaveSubtypePcm = {
    0x00000001,
    0x0000,
    0x0010,
    {0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71},
};

constexpr GUID kWaveSubtypeIeeeFloat = {
    0x00000003,
    0x0000,
    0x0010,
    {0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71},
};

int HResultCode(HRESULT result) {
  return static_cast<int>(static_cast<std::int32_t>(result));
}

std::wstring Utf8ToWide(const std::string& value) {
  if (value.empty()) {
    return {};
  }
  const int required =
      MultiByteToWideChar(CP_UTF8, 0, value.c_str(), -1, nullptr, 0);
  if (required <= 1) {
    return {};
  }
  std::wstring converted(static_cast<std::size_t>(required - 1), L'\0');
  MultiByteToWideChar(CP_UTF8, 0, value.c_str(), -1, converted.data(), required);
  return converted;
}

template <typename T>
void SafeRelease(T*& ptr) {
  if (ptr != nullptr) {
    ptr->Release();
    ptr = nullptr;
  }
}

WAVEFORMATEXTENSIBLE WaveFormatFromDescriptor(const FormatDescriptor& descriptor) {
  WAVEFORMATEXTENSIBLE wave{};
  wave.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
  wave.Format.nChannels = static_cast<WORD>(descriptor.channels.channel_count);
  wave.Format.nSamplesPerSec = descriptor.sample_rate_hz;
  wave.Format.wBitsPerSample =
      static_cast<WORD>(descriptor.container_bits_per_sample);
  wave.Format.nBlockAlign =
      static_cast<WORD>((wave.Format.nChannels * wave.Format.wBitsPerSample) / 8);
  wave.Format.nAvgBytesPerSec =
      wave.Format.nSamplesPerSec * wave.Format.nBlockAlign;
  wave.Format.cbSize = sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX);
  wave.Samples.wValidBitsPerSample =
      static_cast<WORD>(descriptor.valid_bits_per_sample);
  wave.dwChannelMask = descriptor.channels.channel_mask;
  wave.SubFormat = descriptor.sample_type == SampleType::kFloat32
                       ? kWaveSubtypeIeeeFloat
                       : kWaveSubtypePcm;
  return wave;
}

class ScopedThreadCom {
 public:
  ScopedThreadCom() {
    result_ = CoInitializeEx(nullptr, COINIT_MULTITHREADED);
    if (result_ == S_OK || result_ == S_FALSE) {
      needs_uninitialize_ = true;
    } else if (result_ == RPC_E_CHANGED_MODE) {
      result_ = S_OK;
    }
  }

  ScopedThreadCom(const ScopedThreadCom&) = delete;
  ScopedThreadCom& operator=(const ScopedThreadCom&) = delete;

  ~ScopedThreadCom() {
    if (needs_uninitialize_) {
      CoUninitialize();
    }
  }

  HRESULT result() const { return result_; }

 private:
  HRESULT result_ = E_FAIL;
  bool needs_uninitialize_ = false;
};

REFERENCE_TIME MillisecondsToReferenceTime(std::uint32_t milliseconds) {
  return static_cast<REFERENCE_TIME>(
      static_cast<std::uint64_t>(milliseconds) * kHundredNsPerMs);
}

REFERENCE_TIME FramesToReferenceTime(std::uint32_t frames,
                                     std::uint32_t sample_rate_hz) {
  if (sample_rate_hz == 0) {
    return 0;
  }
  const double reference_time =
      (static_cast<double>(kHundredNsPerSecond) *
       static_cast<double>(frames)) /
      static_cast<double>(sample_rate_hz);
  return static_cast<REFERENCE_TIME>(reference_time + 0.5);
}

#endif

std::string BoolString(bool value) {
  return value ? "true" : "false";
}

bool IsDeviceInvalidatedResult(int code) {
#if defined(_WIN32)
  return code == HResultCode(AUDCLNT_E_DEVICE_INVALIDATED) ||
         code == HResultCode(AUDCLNT_E_RESOURCES_INVALIDATED) ||
         code == HResultCode(AUDCLNT_E_SERVICE_NOT_RUNNING);
#else
  (void)code;
  return false;
#endif
}

std::uint64_t DurationFrames(const PlaybackConfig& config) {
  if (config.continuous) {
    return std::numeric_limits<std::uint64_t>::max();
  }
  return std::max<std::uint64_t>(
      1,
      (static_cast<std::uint64_t>(config.format.sample_rate_hz) *
       config.duration_ms) /
          1000);
}

OperationResult ValidateConfigForPlayback(const PlaybackConfig& config) {
  if (config.backend != BackendApi::kWasapiExclusive) {
    return OperationResult::Failure(
        kWasapiInvalidArgument,
        "WASAPI exclusive PCM playback requires BackendApi::kWasapiExclusive");
  }
  if (config.device.stable_id.empty()) {
    return OperationResult::Failure(
        kWasapiInvalidArgument,
        "WASAPI exclusive PCM playback requires an explicit endpoint ID");
  }
  if (config.format.signal_mode != SignalMode::kPcm &&
      config.format.signal_mode != SignalMode::kDop) {
    return OperationResult::Failure(
        kWasapiInvalidArgument,
        "WASAPI exclusive playback slice supports PCM or explicit DoP only");
  }
  if (!IsWasapiExclusivePlaybackFormat(config.format)) {
    return OperationResult::Failure(
        kWasapiInvalidArgument,
        "WASAPI exclusive playback requires a supported PCM format or DoP carrier");
  }
  if (config.format.signal_mode == SignalMode::kDop) {
    if (!std::isfinite(config.frequency_hz) || config.frequency_hz <= 0.0) {
      return OperationResult::Failure(
          kWasapiInvalidArgument,
          "WASAPI exclusive DoP playback requires a positive signal frequency");
    }
    if (!std::isfinite(config.amplitude_dbfs) || config.amplitude_dbfs > 0.0) {
      return OperationResult::Failure(
          kWasapiInvalidArgument,
          "WASAPI exclusive DoP playback requires amplitude <= 0 dBFS");
    }
  }
  if (config.format.sample_rate_hz == 0 ||
      config.format.channels.channel_count == 0) {
    return OperationResult::Failure(
        kWasapiInvalidArgument,
        "WASAPI exclusive playback requires a non-zero sample rate and channel count");
  }
  return OperationResult::Success();
}

bool IsDopMode(const FormatDescriptor& format) {
  return format.signal_mode == SignalMode::kDop;
}

DopConfig DopConfigFromFormat(const FormatDescriptor& format) {
  DopConfig config;
  config.dsd_rate_multiplier = format.dsd_rate_multiplier.value_or(0);
  config.channel_count = format.channels.channel_count;
  config.dsd_byte_order = SampleType::kDsd1BitLsbFirst;
  config.marker_starts_with_0x05 = format.dop_marker_starts_with_0x05;
  return config;
}

std::string FormatSummary(const FormatDescriptor& format) {
  std::ostringstream summary;
  summary << format.sample_rate_hz << " Hz "
          << format.channels.channel_count << " ch "
          << ToString(format.sample_type) << " valid_bits="
          << format.valid_bits_per_sample << " container_bits="
          << format.container_bits_per_sample;
  return summary.str();
}

}  // namespace

WasapiExclusivePcmPolicy MakeWasapiExclusivePcmPolicy(
    const PlaybackConfig& config) {
  WasapiExclusivePcmPolicy policy;
  policy.keep_warm_after_signal = config.hold_mode == HoldMode::kKeepWarmAfterStop;
  policy.release_after_drain = config.hold_mode == HoldMode::kReleaseAfterDrain;
  policy.buffer_duration_ms =
      std::max<std::uint32_t>(1, config.wasapi_exclusive_buffer_duration_ms);
  policy.periodicity_ms = config.wasapi_exclusive_periodicity_ms;
  policy.periodicity_ms =
      std::min(policy.periodicity_ms, policy.buffer_duration_ms);
  policy.render_poll_interval_ms = std::max<std::uint32_t>(
      1,
      config.wasapi_exclusive_render_poll_interval_ms);
  policy.event_callback_enabled =
      config.wasapi_exclusive_event_callback_enabled;
  policy.alignment_retry_enabled =
      config.wasapi_exclusive_alignment_retry_enabled;
  policy.event_wait_timeout_ms = std::max<std::uint32_t>(
      1,
      config.wasapi_exclusive_event_timeout_ms);
  if (policy.event_callback_enabled) {
    policy.periodicity_ms = policy.buffer_duration_ms;
  }
  policy.release_cooldown_ms = config.release_cooldown_ms == 0
                                   ? 1
                                   : config.release_cooldown_ms;
  return policy;
}

bool IsWasapiExclusivePcmPlaybackFormat(const FormatDescriptor& format) {
  return IsRenderablePcmFormat(format);
}

bool IsWasapiExclusiveDopCarrierFormat(const FormatDescriptor& format) {
  if (format.signal_mode != SignalMode::kDop) {
    return false;
  }
  if (format.sample_type != SampleType::kInt24In32 ||
      format.valid_bits_per_sample != 24 ||
      format.container_bits_per_sample != 32) {
    return false;
  }
  if (!format.dsd_rate_multiplier ||
      !IsSupportedDopRate(*format.dsd_rate_multiplier)) {
    return false;
  }
  if (format.sample_rate_hz !=
      DopCarrierSampleRateHz(*format.dsd_rate_multiplier)) {
    return false;
  }
  return format.channels.channel_count > 0;
}

bool IsWasapiExclusivePlaybackFormat(const FormatDescriptor& format) {
  return IsWasapiExclusivePcmPlaybackFormat(format) ||
         IsWasapiExclusiveDopCarrierFormat(format);
}

std::vector<std::uint8_t> ConvertFloat32InterleavedToWasapiPcmBytes(
    const std::vector<float>& interleaved_samples,
    std::uint32_t channel_count,
    const FormatDescriptor& format) {
  return ConvertFloat32InterleavedToPcmBytes(
      interleaved_samples,
      channel_count,
      format);
}

struct WasapiExclusivePcmBackend::Impl {
  ~Impl() { Shutdown(); }

  BackendApi Api() const { return BackendApi::kWasapiExclusive; }

  DeviceList EnumerateDevices() {
    DeviceList devices;
    const auto snapshot = EnumerateWasapiRenderEndpoints();
    devices.reserve(snapshot.devices.size());
    for (auto device_snapshot : snapshot.devices) {
      device_snapshot.device.backend = BackendApi::kWasapiExclusive;
      devices.push_back(device_snapshot.device);
    }
    return devices;
  }

  FormatProbeResult ProbeFormats(const DeviceInfo& device) {
    FormatProbeResult result;
    result.requested = WasapiDefaultPcmCandidate();
    if (device.stable_id.empty()) {
      result.rejection_reasons.push_back(
          "WASAPI exclusive format probe requires an explicit endpoint ID");
      return result;
    }

    WasapiFormatProbeRequest request;
    request.endpoint_id = device.stable_id;
    request.exclusive_mode = true;
    request.candidate_formats = WasapiDefaultPcmCandidates();

    const auto snapshot = ProbeWasapiEndpointFormats(request);
    for (const auto& probe : snapshot.probes) {
      if (probe.support == CapabilitySupport::kSupported &&
          probe.accepted_format) {
        result.supported_formats.push_back(*probe.accepted_format);
      }
      if (probe.error) {
        result.rejection_reasons.push_back(probe.error->message);
      }
    }
    return result;
  }

  OperationResult Initialize(const PlaybackConfig& config) {
    auto validation = ValidateConfigForPlayback(config);
    if (!validation.ok) {
      SetLastError(validation.error);
      return validation;
    }

    Shutdown();

    {
      std::scoped_lock lock(state_mutex_, stats_mutex_, events_mutex_);
      config_ = config;
      policy_ = MakeWasapiExclusivePcmPolicy(config_);
      stats_ = {};
      events_.clear();
      sequence_ = 0;
      state_ = DeviceLifecycleState::kDiscovered;
      signal_frame_target_ = DurationFrames(config_);
      signal_frames_written_ = 0;
      force_silence_ = false;
      last_error_ = {};
      generator_.ResetPhase();
      dop_generator_.Reset();
    }

    if (!TransitionTo(DeviceLifecycleState::kReserved,
                      "selected WASAPI endpoint reserved for exclusive mode")) {
      return OperationResult::Failure(kWasapiInvalidState, GetLastError().message);
    }

#if !defined(_WIN32)
    TransitionTo(DeviceLifecycleState::kFaulted,
                 "WASAPI exclusive playback is not available");
    return Fail(
        kWasapiNotImplemented,
        "WASAPI exclusive playback is available only on Windows");
#else
    HRESULT result = InitializeComIfNeeded();
    if (FAILED(result)) {
      TransitionTo(DeviceLifecycleState::kFaulted, "COM initialization failed");
      return Fail(
          HResultCode(result),
          "failed to initialize COM for WASAPI exclusive playback");
    }

    result = CoCreateInstance(
        kClsidMmDeviceEnumerator,
        nullptr,
        CLSCTX_ALL,
        IID_PPV_ARGS(&enumerator_));
    if (FAILED(result) || enumerator_ == nullptr) {
      TransitionTo(DeviceLifecycleState::kFaulted,
                   "MMDeviceEnumerator creation failed");
      ReleaseInterfaces();
      return Fail(
          HResultCode(result),
          "failed to create MMDeviceEnumerator for WASAPI exclusive playback");
    }

    const std::wstring endpoint_id = Utf8ToWide(config_.device.stable_id);
    result = enumerator_->GetDevice(endpoint_id.c_str(), &endpoint_);
    if (FAILED(result) || endpoint_ == nullptr) {
      TransitionTo(DeviceLifecycleState::kFaulted, "selected endpoint open failed");
      ReleaseInterfaces();
      return Fail(
          HResultCode(result),
          "failed to open selected WASAPI endpoint by ID");
    }

    result = endpoint_->Activate(
        __uuidof(IAudioClient),
        CLSCTX_ALL,
        nullptr,
        reinterpret_cast<void**>(&audio_client_));
    if (FAILED(result) || audio_client_ == nullptr) {
      TransitionTo(DeviceLifecycleState::kFaulted,
                   "IAudioClient activation failed");
      ReleaseInterfaces();
      return Fail(
          HResultCode(result),
          "failed to activate IAudioClient for WASAPI exclusive playback");
    }

    wave_format_ = WaveFormatFromDescriptor(config_.format);
    result = audio_client_->IsFormatSupported(
        AUDCLNT_SHAREMODE_EXCLUSIVE,
        &wave_format_.Format,
        nullptr);
    if (result != S_OK) {
      const int code = HResultCode(result);
      const std::string message = DescribeWasapiAudioClientError(
          code,
          "IAudioClient::IsFormatSupported",
          "exact WASAPI exclusive format support check failed");
      AddErrorEvent(code, "IAudioClient::IsFormatSupported", message);
      TransitionTo(DeviceLifecycleState::kFaulted,
                   std::string("exact exclusive format support check failed: ") +
                       WasapiAudioClientErrorSymbol(code));
      ReleaseInterfaces();
      return Fail(code, message);
    }

    REFERENCE_TIME default_device_period = 0;
    REFERENCE_TIME minimum_device_period = 0;
    result = audio_client_->GetDevicePeriod(
        &default_device_period,
        &minimum_device_period);
    if (FAILED(result)) {
      const int code = HResultCode(result);
      const std::string message = DescribeWasapiAudioClientError(
          code,
          "IAudioClient::GetDevicePeriod",
          "failed to query WASAPI exclusive device period");
      AddErrorEvent(code, "IAudioClient::GetDevicePeriod", message);
      TransitionTo(DeviceLifecycleState::kFaulted,
                   "IAudioClient::GetDevicePeriod exclusive failed");
      ReleaseInterfaces();
      return Fail(code, message);
    }

    const REFERENCE_TIME requested_buffer_duration =
        MillisecondsToReferenceTime(policy_.buffer_duration_ms);
    const REFERENCE_TIME requested_periodicity =
        policy_.event_callback_enabled
            ? requested_buffer_duration
            : (policy_.periodicity_ms == 0
                   ? 0
                   : MillisecondsToReferenceTime(policy_.periodicity_ms));
    REFERENCE_TIME initialize_buffer_duration = requested_buffer_duration;
    REFERENCE_TIME initialize_periodicity = requested_periodicity;
    bool alignment_retry_performed = false;
    std::uint32_t alignment_retry_frames = 0;
    const DWORD stream_flags =
        policy_.event_callback_enabled ? AUDCLNT_STREAMFLAGS_EVENTCALLBACK : 0;
    result = audio_client_->Initialize(
        AUDCLNT_SHAREMODE_EXCLUSIVE,
        stream_flags,
        initialize_buffer_duration,
        initialize_periodicity,
        &wave_format_.Format,
        nullptr);
    if (result == AUDCLNT_E_BUFFER_SIZE_NOT_ALIGNED &&
        policy_.event_callback_enabled &&
        policy_.alignment_retry_enabled) {
      result = audio_client_->GetBufferSize(&alignment_retry_frames);
      if (FAILED(result) || alignment_retry_frames == 0) {
        const int code = HResultCode(result);
        const std::string message = DescribeWasapiAudioClientError(
            code,
            "IAudioClient::GetBufferSize",
            "failed to query aligned WASAPI exclusive event buffer size");
        AddErrorEvent(code, "IAudioClient::GetBufferSize", message);
        TransitionTo(DeviceLifecycleState::kFaulted,
                     "aligned exclusive buffer query failed");
        ReleaseInterfaces();
        return Fail(code, message);
      }

      alignment_retry_performed = true;
      initialize_buffer_duration = FramesToReferenceTime(
          alignment_retry_frames,
          config_.format.sample_rate_hz);
      initialize_periodicity = initialize_buffer_duration;
      AddBufferAlignmentRetryEvent(
          alignment_retry_frames,
          initialize_buffer_duration);

      SafeRelease(audio_client_);
      result = endpoint_->Activate(
          __uuidof(IAudioClient),
          CLSCTX_ALL,
          nullptr,
          reinterpret_cast<void**>(&audio_client_));
      if (FAILED(result) || audio_client_ == nullptr) {
        const int code = HResultCode(result);
        const std::string message = DescribeWasapiAudioClientError(
            code,
            "IMMDevice::Activate",
            "failed to reactivate IAudioClient for aligned WASAPI exclusive event buffer");
        AddErrorEvent(code, "IMMDevice::Activate", message);
        TransitionTo(DeviceLifecycleState::kFaulted,
                     "IAudioClient reactivation for aligned buffer failed");
        ReleaseInterfaces();
        return Fail(code, message);
      }
      result = audio_client_->Initialize(
          AUDCLNT_SHAREMODE_EXCLUSIVE,
          stream_flags,
          initialize_buffer_duration,
          initialize_periodicity,
          &wave_format_.Format,
          nullptr);
    }
    if (FAILED(result)) {
      const int code = HResultCode(result);
      const std::string message = DescribeWasapiAudioClientError(
          code,
          "IAudioClient::Initialize",
          "failed to initialize WASAPI exclusive stream");
      AddErrorEvent(code, "IAudioClient::Initialize", message);
      TransitionTo(DeviceLifecycleState::kFaulted,
                   std::string("IAudioClient::Initialize exclusive failed: ") +
                       WasapiAudioClientErrorSymbol(code));
      ReleaseInterfaces();
      return Fail(code, message);
    }

    if (policy_.event_callback_enabled) {
      render_event_ = CreateEventW(nullptr, FALSE, FALSE, nullptr);
      if (render_event_ == nullptr) {
        const int code = static_cast<int>(::GetLastError());
        AddErrorEvent(code, "CreateEventW",
                      "failed to create WASAPI exclusive render event");
        TransitionTo(DeviceLifecycleState::kFaulted,
                     "WASAPI exclusive render event creation failed");
        ReleaseInterfaces();
        return Fail(code, "failed to create WASAPI exclusive render event");
      }
      result = audio_client_->SetEventHandle(render_event_);
      if (FAILED(result)) {
        const int code = HResultCode(result);
        const std::string message = DescribeWasapiAudioClientError(
            code,
            "IAudioClient::SetEventHandle",
            "failed to set WASAPI exclusive render event handle");
        AddErrorEvent(code, "IAudioClient::SetEventHandle", message);
        TransitionTo(DeviceLifecycleState::kFaulted,
                     "IAudioClient::SetEventHandle exclusive failed");
        ReleaseInterfaces();
        return Fail(code, message);
      }
    }

    result = audio_client_->GetBufferSize(&buffer_frames_);
    if (FAILED(result) || buffer_frames_ == 0) {
      TransitionTo(DeviceLifecycleState::kFaulted,
                   "IAudioClient::GetBufferSize failed");
      ReleaseInterfaces();
      return Fail(
          HResultCode(result),
          "failed to query WASAPI exclusive buffer size");
    }

    result = audio_client_->GetService(
        __uuidof(IAudioRenderClient),
        reinterpret_cast<void**>(&render_client_));
    if (FAILED(result) || render_client_ == nullptr) {
      TransitionTo(DeviceLifecycleState::kFaulted,
                   "IAudioRenderClient service failed");
      ReleaseInterfaces();
      return Fail(HResultCode(result), "failed to acquire IAudioRenderClient");
    }

    {
      std::lock_guard lock(stats_mutex_);
      stats_.expected_callback_interval_ms =
          1000.0 * static_cast<double>(buffer_frames_) /
          static_cast<double>(config_.format.sample_rate_hz);
    }

    if (!TransitionTo(DeviceLifecycleState::kPrepared,
                      "WASAPI exclusive stream initialized once")) {
      ReleaseInterfaces();
      return OperationResult::Failure(kWasapiInvalidState, GetLastError().message);
    }
    const REFERENCE_TIME actual_buffer_duration =
        FramesToReferenceTime(buffer_frames_, config_.format.sample_rate_hz);
    AddInitializationEvent(requested_buffer_duration,
                           requested_periodicity,
                           initialize_buffer_duration,
                           initialize_periodicity,
                           default_device_period,
                           minimum_device_period,
                           actual_buffer_duration,
                           alignment_retry_performed,
                           alignment_retry_frames);
    return OperationResult::Success();
#endif
  }

  OperationResult Start() {
#if !defined(_WIN32)
    return Fail(kWasapiNotImplemented,
                "WASAPI exclusive playback is available only on Windows");
#else
    const auto current = GetState();
    if (current == DeviceLifecycleState::kRunningSilence &&
        render_thread_.joinable()) {
      return Fail(
          kWasapiInvalidState,
          "WASAPI exclusive RunningSilence restart requires explicit release before rerun");
    }
    if (current != DeviceLifecycleState::kPrepared &&
        current != DeviceLifecycleState::kHeldOpen) {
      return Fail(kWasapiInvalidState,
                  "WASAPI exclusive stream must be prepared before start");
    }
    if (audio_client_ == nullptr || render_client_ == nullptr) {
      return Fail(kWasapiNotInitialized,
                  "WASAPI exclusive stream is not initialized");
    }

    force_silence_ = false;
    render_thread_stop_ = false;
    signal_frames_written_ = 0;
    generator_.ResetPhase();
    dop_generator_.Reset();
    last_callback_time_ = std::chrono::steady_clock::now();

    if (!TransitionTo(DeviceLifecycleState::kRunningSignal,
                      IsDopMode(config_.format)
                          ? "WASAPI exclusive DoP carrier signal started"
                          : "WASAPI exclusive 1 kHz signal started")) {
      return OperationResult::Failure(kWasapiInvalidState, GetLastError().message);
    }

    if (!FillRenderBuffer(buffer_frames_)) {
      TransitionTo(DeviceLifecycleState::kFaulted,
                   "initial WASAPI exclusive render fill failed");
      return OperationResult::Failure(kWasapiInvalidState, GetLastError().message);
    }

    const HRESULT result = audio_client_->Start();
    if (FAILED(result)) {
      TransitionTo(DeviceLifecycleState::kFaulted,
                   "IAudioClient::Start exclusive failed");
      return Fail(HResultCode(result),
                  "failed to start WASAPI exclusive stream");
    }

    render_thread_ = std::thread([this] { RenderLoop(); });
    return OperationResult::Success();
#endif
  }

  OperationResult Stop() {
    const auto current = GetState();
    if (current == DeviceLifecycleState::kRunningSignal &&
        policy_.keep_warm_after_signal) {
      force_silence_ = true;
      if (!TransitionTo(DeviceLifecycleState::kRunningSilence,
                        IsDopMode(config_.format)
                            ? "normal stop switched to valid DoP silence keep-warm"
                            : "normal stop switched to valid PCM silence keep-warm")) {
        return OperationResult::Failure(kWasapiInvalidState, GetLastError().message);
      }
      return OperationResult::Success();
    }
    if (current == DeviceLifecycleState::kRunningSilence &&
        policy_.keep_warm_after_signal) {
      return OperationResult::Success();
    }

    if (current == DeviceLifecycleState::kRunningSignal ||
        current == DeviceLifecycleState::kRunningSilence) {
      if (!TransitionTo(DeviceLifecycleState::kDraining,
                        "WASAPI exclusive stream draining before stop")) {
        return OperationResult::Failure(kWasapiInvalidState, GetLastError().message);
      }
      StopRenderThread();
#if defined(_WIN32)
      if (audio_client_ != nullptr) {
        const HRESULT result = audio_client_->Stop();
        if (FAILED(result)) {
          TransitionTo(DeviceLifecycleState::kFaulted,
                       "IAudioClient::Stop exclusive failed");
          return Fail(HResultCode(result),
                      "failed to stop WASAPI exclusive stream");
        }
      }
#endif
    }

    if (policy_.release_after_drain) {
      return ReleaseAfterDrain();
    }

    if (GetState() != DeviceLifecycleState::kHeldOpen) {
      if (!TransitionTo(DeviceLifecycleState::kHeldOpen,
                        "WASAPI exclusive stream held initialized after stop")) {
        return OperationResult::Failure(kWasapiInvalidState, GetLastError().message);
      }
    }
    return OperationResult::Success();
  }

  OperationResult Reset() {
    return Fail(
        kWasapiResetDisabled,
        "WASAPI exclusive normal reset is disabled; use drain/keep-warm/release lifecycle");
  }

  RealtimeStats GetRealtimeStats() const {
    std::lock_guard lock(stats_mutex_);
    return stats_;
  }

  BackendError GetLastError() const {
    std::lock_guard lock(error_mutex_);
    return last_error_;
  }

  OperationResult Shutdown() {
    const auto current = GetState();
    if (current == DeviceLifecycleState::kDiscovered ||
        current == DeviceLifecycleState::kReleased) {
      return OperationResult::Success();
    }

    if (current == DeviceLifecycleState::kRunningSignal ||
        current == DeviceLifecycleState::kRunningSilence) {
      if (!TransitionTo(DeviceLifecycleState::kDraining,
                        "WASAPI exclusive stream draining before release")) {
        return OperationResult::Failure(kWasapiInvalidState, GetLastError().message);
      }
    }

    StopRenderThread();
#if defined(_WIN32)
    if (audio_client_ != nullptr) {
      const HRESULT result = audio_client_->Stop();
      if (FAILED(result) && !IsDeviceInvalidatedResult(HResultCode(result))) {
        TransitionTo(DeviceLifecycleState::kFaulted,
                     "IAudioClient::Stop failed during exclusive shutdown");
        ReleaseInterfaces();
        return Fail(
            HResultCode(result),
            "failed to stop WASAPI exclusive stream during shutdown");
      }
    }
#endif
    return ReleaseAfterDrain();
  }

  DeviceLifecycleState GetState() const {
    std::lock_guard lock(state_mutex_);
    return state_;
  }

  std::vector<DiagnosticEvent> GetEvents() const {
    std::lock_guard lock(events_mutex_);
    return events_;
  }

 private:
  OperationResult Fail(int code, std::string message) {
    SetLastError({code, std::move(message)});
    return OperationResult::Failure(code, GetLastError().message);
  }

  void SetLastError(BackendError error) {
    std::lock_guard lock(error_mutex_);
    last_error_ = std::move(error);
  }

  bool TransitionTo(DeviceLifecycleState next, std::string message) {
    DeviceLifecycleState previous;
    {
      std::lock_guard lock(state_mutex_);
      previous = state_;
      LifecyclePolicy lifecycle_policy;
      lifecycle_policy.known_problem_device =
          config_.device.is_known_problem_device;
      const auto decision = EvaluateTransition(previous, next, lifecycle_policy);
      if (!decision.allowed) {
        SetLastError({kWasapiInvalidState, decision.reason});
        return false;
      }
      state_ = next;
    }

    auto event = MakeLifecycleEvent(
        NextSequence(),
        BackendApi::kWasapiExclusive,
        config_.device.stable_id,
        previous,
        next,
        std::move(message));
    event.backend_fields["hold_mode"] = ToString(config_.hold_mode);
    event.backend_fields["reset_used"] = "false";
    event.backend_fields["share_mode"] = "exclusive";
    event.backend_fields["signal_mode"] = ToString(config_.format.signal_mode);
    event.backend_fields["keep_alive_format"] = IsDopMode(config_.format)
        ? "valid-dop-silence"
        : "valid-pcm-silence";
    AppendEvent(std::move(event));
    SetLastError({});
    return true;
  }

  std::uint64_t NextSequence() { return ++sequence_; }

  void AppendEvent(DiagnosticEvent event) {
    std::lock_guard lock(events_mutex_);
    events_.push_back(std::move(event));
  }

  void AddInitializationEvent(std::int64_t requested_buffer_duration_100ns,
                              std::int64_t requested_periodicity_100ns,
                              std::int64_t initialize_buffer_duration_100ns,
                              std::int64_t initialize_periodicity_100ns,
                              std::int64_t default_device_period_100ns,
                              std::int64_t minimum_device_period_100ns,
                              std::int64_t actual_buffer_duration_100ns,
                              bool alignment_retry_performed,
                              std::uint32_t alignment_retry_frames) {
    DiagnosticEvent event;
    event.type = DiagnosticEventType::kFormatProbe;
    event.sequence = NextSequence();
    event.backend = BackendApi::kWasapiExclusive;
    event.device_id = config_.device.stable_id;
    event.format = config_.format;
    event.message = IsDopMode(config_.format)
        ? "WASAPI exclusive DoP carrier stream initialized"
        : "WASAPI exclusive PCM stream initialized";
    event.backend_fields["requested_format"] = FormatSummary(config_.format);
    event.backend_fields["accepted_format"] = FormatSummary(config_.format);
    event.backend_fields["exact_format_supported"] = "true";
    event.backend_fields["share_mode"] = "exclusive";
    event.backend_fields["signal_mode"] = ToString(config_.format.signal_mode);
    event.backend_fields["fallback_shared"] = "false";
    event.backend_fields["fallback_format"] = "false";
    event.backend_fields["keep_alive_format"] = IsDopMode(config_.format)
        ? "valid-dop-silence"
        : "valid-pcm-silence";
    if (config_.format.signal_mode == SignalMode::kDop) {
      const auto dop_config = DopConfigFromFormat(config_.format);
      event.backend_fields["dop_dsd_rate_multiplier"] =
          std::to_string(dop_config.dsd_rate_multiplier);
      event.backend_fields["dop_marker_first"] =
          dop_config.marker_starts_with_0x05 ? "0x05" : "0xFA";
      event.backend_fields["dop_dsd_byte_order"] =
          ToString(dop_config.dsd_byte_order);
      event.backend_fields["pcm_carrier_sample_type"] =
          ToString(config_.format.sample_type);
    }
    event.backend_fields["requested_buffer_duration_100ns"] =
        std::to_string(requested_buffer_duration_100ns);
    event.backend_fields["requested_periodicity_100ns"] =
        std::to_string(requested_periodicity_100ns);
    event.backend_fields["initialize_buffer_duration_100ns"] =
        std::to_string(initialize_buffer_duration_100ns);
    event.backend_fields["initialize_periodicity_100ns"] =
        std::to_string(initialize_periodicity_100ns);
    event.backend_fields["device_default_period_100ns"] =
        std::to_string(default_device_period_100ns);
    event.backend_fields["device_minimum_period_100ns"] =
        std::to_string(minimum_device_period_100ns);
    event.backend_fields["actual_buffer_duration_100ns"] =
        std::to_string(actual_buffer_duration_100ns);
    event.backend_fields["buffer_frames"] = std::to_string(buffer_frames_);
    event.backend_fields["drive_mode"] = policy_.event_callback_enabled
        ? "event-callback"
        : "timer-poll";
    event.backend_fields["event_callback"] =
        BoolString(policy_.event_callback_enabled);
    event.backend_fields["alignment_retry_enabled"] =
        BoolString(policy_.alignment_retry_enabled);
    event.backend_fields["alignment_retry_performed"] =
        BoolString(alignment_retry_performed);
    event.backend_fields["alignment_retry_frames"] =
        std::to_string(alignment_retry_frames);
    event.backend_fields["event_wait_timeout_ms"] =
        std::to_string(policy_.event_wait_timeout_ms);
    event.backend_fields["render_poll_interval_ms"] =
        std::to_string(policy_.render_poll_interval_ms);
    event.backend_fields["audio_thread_mmcss_enabled"] =
        config_.audio_thread_mmcss_enabled ? "true" : "false";
    event.backend_fields["audio_thread_mmcss_task_name"] =
        config_.audio_thread_mmcss_task_name;
    event.backend_fields["audio_thread_mmcss_priority"] =
        std::to_string(config_.audio_thread_mmcss_priority);
    AddHighLoadDiagnosticFields(config_, event.backend_fields);
    AppendEvent(std::move(event));
  }

  void AddThreadSchedulingEvent(
      const AudioThreadMmcssRegistrationSnapshot& snapshot,
      std::string message) {
    DiagnosticEvent event;
    event.type = DiagnosticEventType::kRuntimeStats;
    event.sequence = NextSequence();
    event.backend = BackendApi::kWasapiExclusive;
    event.device_id = config_.device.stable_id;
    event.message = std::move(message);
    event.backend_fields["api"] = "AvSetMmThreadCharacteristics";
    event.backend_fields["thread_role"] = "WASAPI exclusive render thread";
    AddAudioThreadMmcssBackendFields(event.backend_fields, snapshot);
    AppendEvent(std::move(event));
  }

  void AddBufferAlignmentRetryEvent(std::uint32_t aligned_frames,
                                    std::int64_t aligned_duration_100ns) {
    DiagnosticEvent event;
    event.type = DiagnosticEventType::kFormatProbe;
    event.sequence = NextSequence();
    event.backend = BackendApi::kWasapiExclusive;
    event.device_id = config_.device.stable_id;
    event.format = config_.format;
    event.message =
        "WASAPI exclusive event buffer size was realigned for the device";
    event.backend_fields["api"] = "IAudioClient::Initialize";
    event.backend_fields["symbol"] = "AUDCLNT_E_BUFFER_SIZE_NOT_ALIGNED";
    event.backend_fields["aligned_buffer_frames"] =
        std::to_string(aligned_frames);
    event.backend_fields["aligned_buffer_duration_100ns"] =
        std::to_string(aligned_duration_100ns);
    event.backend_fields["reactivated_audio_client"] = "true";
    AppendEvent(std::move(event));
  }

  void AddRuntimeEvent(std::uint32_t padding_frames,
                       std::uint32_t available_frames,
                       std::uint32_t submitted_frames) {
    const auto stats = GetRealtimeStats();
    if (stats.callback_count > 8 && (stats.callback_count % 50) != 0) {
      return;
    }

    DiagnosticEvent event;
    event.type = DiagnosticEventType::kRuntimeStats;
    event.sequence = NextSequence();
    event.backend = BackendApi::kWasapiExclusive;
    event.device_id = config_.device.stable_id;
    event.message = "WASAPI exclusive buffer update";
    event.realtime_stats = stats;
    event.backend_fields["buffer_frames"] = std::to_string(buffer_frames_);
    event.backend_fields["padding_frames"] = std::to_string(padding_frames);
    event.backend_fields["available_frames"] = std::to_string(available_frames);
    event.backend_fields["submitted_frames"] = std::to_string(submitted_frames);
    event.backend_fields["signal_mode"] = ToString(config_.format.signal_mode);
    AddHighLoadDiagnosticFields(config_, event.backend_fields);
    if (HighLoadLateCallbackJustOccurred(config_, stats)) {
      event.backend_fields["late_callback"] = "true";
      event.backend_fields["late_callback_source"] =
          "high_load_render_delay";
    }
    if (IsDopMode(config_.format)) {
      event.backend_fields["keep_alive_format"] = "valid-dop-silence";
      event.backend_fields["dop_next_marker_frame"] =
          std::to_string(dop_generator_.next_dop_frame_index());
    }
    AppendEvent(std::move(event));
  }

  void AddErrorEvent(int code, std::string api, std::string message) {
    DiagnosticEvent event;
    event.type = DiagnosticEventType::kError;
    event.sequence = NextSequence();
    event.backend = BackendApi::kWasapiExclusive;
    event.device_id = config_.device.stable_id;
    event.message = message;
    event.backend_fields["api"] = std::move(api);
    event.backend_fields["code"] = std::to_string(code);
    event.backend_fields["symbol"] = WasapiAudioClientErrorSymbol(code);
    event.backend_fields["device_invalidated"] =
        IsDeviceInvalidatedResult(code) ? "true" : "false";
    AppendEvent(std::move(event));
  }

#if defined(_WIN32)
  HRESULT InitializeComIfNeeded() {
    if (com_ready_) {
      return S_OK;
    }
    const HRESULT result = CoInitializeEx(nullptr, COINIT_MULTITHREADED);
    if (result == S_OK || result == S_FALSE) {
      com_ready_ = true;
      com_needs_uninitialize_ = true;
      return S_OK;
    }
    if (result == RPC_E_CHANGED_MODE) {
      com_ready_ = true;
      com_needs_uninitialize_ = false;
      return S_OK;
    }
    return result;
  }

  void ReleaseInterfaces() {
    SafeRelease(render_client_);
    SafeRelease(audio_client_);
    SafeRelease(endpoint_);
    SafeRelease(enumerator_);
    if (render_event_ != nullptr) {
      CloseHandle(render_event_);
      render_event_ = nullptr;
    }
    buffer_frames_ = 0;
    if (com_needs_uninitialize_) {
      CoUninitialize();
    }
    com_ready_ = false;
    com_needs_uninitialize_ = false;
  }
#else
  void ReleaseInterfaces() {}
#endif

  OperationResult ReleaseAfterDrain() {
    const auto current = GetState();
    if (current == DeviceLifecycleState::kFaulted) {
      StopRenderThread();
      ReleaseInterfaces();
      if (!TransitionTo(DeviceLifecycleState::kReleased,
                        "faulted WASAPI exclusive resources released once")) {
        return OperationResult::Failure(kWasapiInvalidState, GetLastError().message);
      }
      return OperationResult::Success();
    }

    if (current != DeviceLifecycleState::kReleasing &&
        current != DeviceLifecycleState::kReleased) {
      if (!TransitionTo(DeviceLifecycleState::kReleasing,
                        "WASAPI exclusive resources releasing after drain")) {
        return OperationResult::Failure(kWasapiInvalidState, GetLastError().message);
      }
    }

    if (policy_.release_cooldown_ms > 0) {
      std::this_thread::sleep_for(
          std::chrono::milliseconds(policy_.release_cooldown_ms));
    }
    ReleaseInterfaces();
    if (!TransitionTo(DeviceLifecycleState::kReleased,
                      "WASAPI exclusive resources released once")) {
      return OperationResult::Failure(kWasapiInvalidState, GetLastError().message);
    }
    return OperationResult::Success();
  }

  void StopRenderThread() {
    render_thread_stop_ = true;
#if defined(_WIN32)
    if (render_event_ != nullptr) {
      SetEvent(render_event_);
    }
#endif
    if (render_thread_.joinable()) {
      render_thread_.join();
    }
  }

#if defined(_WIN32)
  bool FillRenderBuffer(std::uint32_t frames) {
    if (frames == 0) {
      return true;
    }
    BYTE* raw_buffer = nullptr;
    HRESULT result = render_client_->GetBuffer(frames, &raw_buffer);
    if (FAILED(result) || raw_buffer == nullptr) {
      const int code = HResultCode(result);
      AddErrorEvent(code, "IAudioRenderClient::GetBuffer",
                    "failed to acquire WASAPI exclusive render buffer");
      SetLastError({code, "failed to acquire WASAPI exclusive render buffer"});
      return false;
    }

    const std::uint64_t written = signal_frames_written_.load();
    const bool silence_only = force_silence_ || written >= signal_frame_target_;
    const std::uint32_t signal_frames = silence_only
        ? 0
        : static_cast<std::uint32_t>(std::min<std::uint64_t>(
              frames,
              signal_frame_target_ - written));

    if (IsDopMode(config_.format)) {
      if (!WriteDopSignalAndSilence(raw_buffer, frames, signal_frames)) {
        render_client_->ReleaseBuffer(frames, 0);
        return false;
      }
      result = render_client_->ReleaseBuffer(frames, 0);
      signal_frames_written_ += signal_frames;
    } else if (signal_frames == 0) {
      result = render_client_->ReleaseBuffer(frames, AUDCLNT_BUFFERFLAGS_SILENT);
    } else {
      if (!WritePcmSignalAndSilence(raw_buffer, frames, signal_frames)) {
        render_client_->ReleaseBuffer(frames, AUDCLNT_BUFFERFLAGS_SILENT);
        return false;
      }
      result = render_client_->ReleaseBuffer(frames, 0);
      signal_frames_written_ += signal_frames;
    }

    if (FAILED(result)) {
      const int code = HResultCode(result);
      AddErrorEvent(code, "IAudioRenderClient::ReleaseBuffer",
                    "failed to release WASAPI exclusive render buffer");
      SetLastError({code, "failed to release WASAPI exclusive render buffer"});
      return false;
    }

    {
      std::lock_guard lock(stats_mutex_);
      stats_.frames_generated += signal_frames;
      stats_.frames_submitted += frames;
      stats_.frames_accepted += frames;
      ++stats_.callback_count;
      const auto now = std::chrono::steady_clock::now();
      const double interval_ms =
          std::chrono::duration<double, std::milli>(
              now - last_callback_time_).count();
      stats_.last_callback_interval_ms = interval_ms;
      stats_.max_callback_delay_ms =
          std::max(stats_.max_callback_delay_ms, interval_ms);
      CountHighLoadLateCallbackIfNeeded(config_, stats_);
      last_callback_time_ = now;
    }

    if (GetState() == DeviceLifecycleState::kRunningSignal &&
        (force_silence_ ||
         signal_frames_written_.load() >= signal_frame_target_)) {
      if (policy_.keep_warm_after_signal) {
        TransitionTo(DeviceLifecycleState::kRunningSilence,
                     IsDopMode(config_.format)
                         ? "signal ended; valid DoP silence keep-warm is running"
                         : "signal ended; valid PCM silence keep-warm is running");
      } else {
        TransitionTo(DeviceLifecycleState::kHeldOpen,
                     "signal ended; exclusive stream remains initialized");
        render_thread_stop_ = true;
      }
    }
    return true;
  }

  bool WritePcmSignalAndSilence(BYTE* raw_buffer,
                                std::uint32_t total_frames,
                                std::uint32_t signal_frames) {
    const auto& format = config_.format;
    const std::uint32_t channels = format.channels.channel_count;
    const std::size_t total_bytes =
        static_cast<std::size_t>(total_frames) * wave_format_.Format.nBlockAlign;
    std::memset(raw_buffer, 0, total_bytes);

    PcmSineConfig sine_config;
    sine_config.sample_rate_hz = format.sample_rate_hz;
    sine_config.channel_count = channels;
    sine_config.frequency_hz = config_.frequency_hz;
    sine_config.amplitude_dbfs = config_.amplitude_dbfs;
    if (config_.left_channel_enabled && !config_.right_channel_enabled) {
      sine_config.channel_assignment = ChannelAssignment::kLeftOnly;
    } else if (!config_.left_channel_enabled && config_.right_channel_enabled) {
      sine_config.channel_assignment = ChannelAssignment::kRightOnly;
    }
    sine_config.invert_right = config_.invert_right_phase;
    sine_config.right_channel_phase_offset_degrees =
        config_.right_channel_phase_offset_degrees;
    const auto samples =
        generator_.GenerateInterleavedFloat32(sine_config, signal_frames);

    const auto bytes = ConvertFloat32InterleavedToWasapiPcmBytes(
        samples,
        channels,
        format);
    if (bytes.empty() && !samples.empty()) {
      AddErrorEvent(kWasapiInvalidArgument,
                    "ConvertFloat32InterleavedToWasapiPcmBytes",
                    "failed to convert generated PCM signal to WASAPI container");
      SetLastError({kWasapiInvalidArgument,
                    "failed to convert generated PCM signal to WASAPI container"});
      return false;
    }
    if (!bytes.empty()) {
      std::memcpy(raw_buffer, bytes.data(), bytes.size());
    }
    return true;
  }

  bool WriteDopSignalAndSilence(BYTE* raw_buffer,
                                std::uint32_t total_frames,
                                std::uint32_t signal_frames) {
    const auto& format = config_.format;
    const std::size_t total_bytes =
        static_cast<std::size_t>(total_frames) * wave_format_.Format.nBlockAlign;
    std::memset(raw_buffer, 0, total_bytes);

    const DopConfig dop_config = DopConfigFromFormat(format);
    std::size_t offset = 0;
    if (signal_frames > 0) {
      DopSineConfig sine_config;
      sine_config.dop = dop_config;
      sine_config.frequency_hz = config_.frequency_hz;
      sine_config.amplitude_dbfs = config_.amplitude_dbfs;
      auto signal = dop_generator_.GenerateSine(sine_config, signal_frames);
      if (!signal.ok) {
        AddErrorEvent(kWasapiInvalidArgument,
                      "DopSineGenerator::GenerateSine",
                      signal.error);
        SetLastError({kWasapiInvalidArgument, signal.error});
        return false;
      }
      if (signal.bytes.size() > total_bytes) {
        AddErrorEvent(kWasapiInvalidArgument,
                      "DopSineGenerator::GenerateSine",
                      "generated DoP signal exceeds render buffer");
        SetLastError({kWasapiInvalidArgument,
                      "generated DoP signal exceeds render buffer"});
        return false;
      }
      std::memcpy(raw_buffer, signal.bytes.data(), signal.bytes.size());
      offset = signal.bytes.size();
    }

    const std::uint32_t silence_frames = total_frames - signal_frames;
    if (silence_frames > 0) {
      auto silence = dop_generator_.GenerateSilence(dop_config, silence_frames);
      if (!silence.ok) {
        AddErrorEvent(kWasapiInvalidArgument,
                      "DopSineGenerator::GenerateSilence",
                      silence.error);
        SetLastError({kWasapiInvalidArgument, silence.error});
        return false;
      }
      if (offset + silence.bytes.size() > total_bytes) {
        AddErrorEvent(kWasapiInvalidArgument,
                      "DopSineGenerator::GenerateSilence",
                      "generated DoP silence exceeds render buffer");
        SetLastError({kWasapiInvalidArgument,
                      "generated DoP silence exceeds render buffer"});
        return false;
      }
      std::memcpy(raw_buffer + offset, silence.bytes.data(), silence.bytes.size());
    }
    return true;
  }

  void MarkRenderWriteFailure() {
    const auto error = GetLastError();
    {
      std::lock_guard lock(stats_mutex_);
      if (IsDeviceInvalidatedResult(error.code)) {
        ++stats_.device_invalidated_count;
      } else {
        ++stats_.discontinuity_count;
      }
    }
    TransitionTo(DeviceLifecycleState::kFaulted,
                 "WASAPI exclusive render write failed");
    render_thread_stop_ = true;
  }

  void RenderEventDrivenLoop() {
    while (!render_thread_stop_) {
      if (render_event_ == nullptr) {
        AddErrorEvent(kWasapiInvalidState,
                      "IAudioClient::SetEventHandle",
                      "WASAPI exclusive event-driven loop has no event handle");
        TransitionTo(DeviceLifecycleState::kFaulted,
                     "WASAPI exclusive event handle missing");
        render_thread_stop_ = true;
        break;
      }

      const DWORD wait_result =
          WaitForSingleObject(render_event_, policy_.event_wait_timeout_ms);
      if (render_thread_stop_) {
        break;
      }
      if (wait_result != WAIT_OBJECT_0) {
        const int code = wait_result == WAIT_FAILED
                             ? static_cast<int>(::GetLastError())
                             : static_cast<int>(wait_result);
        {
          std::lock_guard lock(stats_mutex_);
          ++stats_.underrun_count;
        }
        AddErrorEvent(code,
                      "WaitForSingleObject",
                      wait_result == WAIT_TIMEOUT
                          ? "WASAPI exclusive render event timed out"
                          : "WASAPI exclusive render event wait failed");
        TransitionTo(DeviceLifecycleState::kFaulted,
                     "WASAPI exclusive render event wait failed");
        render_thread_stop_ = true;
        break;
      }

      ApplyHighLoadRenderDelay(config_, GetRealtimeStats().callback_count);
      if (!FillRenderBuffer(buffer_frames_)) {
        MarkRenderWriteFailure();
        break;
      }
      AddRuntimeEvent(0, buffer_frames_, buffer_frames_);
    }
  }

  void RenderLoop() {
    ScopedThreadCom com;
    if (FAILED(com.result())) {
      const int code = HResultCode(com.result());
      AddErrorEvent(code, "CoInitializeEx",
                    "failed to initialize COM on WASAPI exclusive render thread");
      TransitionTo(DeviceLifecycleState::kFaulted,
                   "WASAPI exclusive render thread COM initialization failed");
      return;
    }
    ScopedAudioThreadMmcssRegistration mmcss({
        config_.audio_thread_mmcss_enabled,
        config_.audio_thread_mmcss_task_name,
        config_.audio_thread_mmcss_priority,
    });
    AddThreadSchedulingEvent(
        mmcss.snapshot(),
        "WASAPI exclusive render thread MMCSS registration evaluated");

    if (policy_.event_callback_enabled) {
      RenderEventDrivenLoop();
      AddThreadSchedulingEvent(
          mmcss.Revert(),
          "WASAPI exclusive render thread MMCSS registration reverted");
      return;
    }

    while (!render_thread_stop_) {
      std::uint32_t padding_frames = 0;
      const HRESULT padding_result =
          audio_client_->GetCurrentPadding(&padding_frames);
      if (FAILED(padding_result)) {
        const int code = HResultCode(padding_result);
        {
          std::lock_guard lock(stats_mutex_);
          if (IsDeviceInvalidatedResult(code)) {
            ++stats_.device_invalidated_count;
          } else {
            ++stats_.discontinuity_count;
          }
        }
        AddErrorEvent(code, "IAudioClient::GetCurrentPadding",
                      "failed to query WASAPI exclusive padding");
        TransitionTo(DeviceLifecycleState::kFaulted,
                     IsDeviceInvalidatedResult(code)
                         ? "WASAPI endpoint invalidated during exclusive playback"
                         : "WASAPI exclusive padding query failed");
        render_thread_stop_ = true;
        break;
      }

      const std::uint32_t available_frames =
          buffer_frames_ > padding_frames ? buffer_frames_ - padding_frames : 0;
      if (available_frames > 0) {
        ApplyHighLoadRenderDelay(config_, GetRealtimeStats().callback_count);
        if (!FillRenderBuffer(available_frames)) {
          MarkRenderWriteFailure();
          break;
        }
      }
      AddRuntimeEvent(padding_frames, available_frames, available_frames);
      std::this_thread::sleep_for(
          std::chrono::milliseconds(policy_.render_poll_interval_ms));
    }
    AddThreadSchedulingEvent(
        mmcss.Revert(),
        "WASAPI exclusive render thread MMCSS registration reverted");
  }
#endif

  mutable std::mutex state_mutex_;
  mutable std::mutex stats_mutex_;
  mutable std::mutex error_mutex_;
  mutable std::mutex events_mutex_;
  PlaybackConfig config_;
  WasapiExclusivePcmPolicy policy_;
  RealtimeStats stats_;
  BackendError last_error_;
  std::vector<DiagnosticEvent> events_;
  std::atomic<std::uint64_t> sequence_{0};
  DeviceLifecycleState state_ = DeviceLifecycleState::kDiscovered;
  PcmSineGenerator generator_;
  DopSineGenerator dop_generator_;
  std::uint64_t signal_frame_target_ = 0;
  std::atomic<std::uint64_t> signal_frames_written_{0};
  std::atomic<bool> render_thread_stop_{false};
  std::atomic<bool> force_silence_{false};
  std::thread render_thread_;
  std::chrono::steady_clock::time_point last_callback_time_ =
      std::chrono::steady_clock::now();

#if defined(_WIN32)
  bool com_ready_ = false;
  bool com_needs_uninitialize_ = false;
  IMMDeviceEnumerator* enumerator_ = nullptr;
  IMMDevice* endpoint_ = nullptr;
  IAudioClient* audio_client_ = nullptr;
  IAudioRenderClient* render_client_ = nullptr;
  HANDLE render_event_ = nullptr;
  WAVEFORMATEXTENSIBLE wave_format_{};
  std::uint32_t buffer_frames_ = 0;
#endif
};

WasapiExclusivePcmBackend::WasapiExclusivePcmBackend()
    : impl_(std::make_unique<Impl>()) {}

WasapiExclusivePcmBackend::~WasapiExclusivePcmBackend() = default;

BackendApi WasapiExclusivePcmBackend::api() const {
  return impl_->Api();
}

DeviceList WasapiExclusivePcmBackend::enumerateDevices() {
  return impl_->EnumerateDevices();
}

FormatProbeResult WasapiExclusivePcmBackend::probeFormats(const DeviceInfo& device) {
  return impl_->ProbeFormats(device);
}

OperationResult WasapiExclusivePcmBackend::initialize(
    const PlaybackConfig& config) {
  return impl_->Initialize(config);
}

OperationResult WasapiExclusivePcmBackend::start() {
  return impl_->Start();
}

OperationResult WasapiExclusivePcmBackend::stop() {
  return impl_->Stop();
}

OperationResult WasapiExclusivePcmBackend::reset() {
  return impl_->Reset();
}

RealtimeStats WasapiExclusivePcmBackend::getRealtimeStats() const {
  return impl_->GetRealtimeStats();
}

BackendError WasapiExclusivePcmBackend::getLastError() const {
  return impl_->GetLastError();
}

OperationResult WasapiExclusivePcmBackend::shutdown() {
  return impl_->Shutdown();
}

DeviceLifecycleState WasapiExclusivePcmBackend::lifecycle_state() const {
  return impl_->GetState();
}

std::vector<DiagnosticEvent> WasapiExclusivePcmBackend::diagnostic_events() const {
  return impl_->GetEvents();
}

}  // namespace aptt
