#include "backends/kernel_streaming_pcm_backend.h"

#include <algorithm>
#include <atomic>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <limits>
#include <mutex>
#include <optional>
#include <sstream>
#include <string_view>
#include <thread>
#include <utility>

#include "backends/audio_thread_scheduling.h"
#include "backends/kernel_streaming_discovery.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>
#if defined(__has_include)
#if __has_include(<ks.h>) && __has_include(<ksmedia.h>)
#define APTT_HAS_WINDOWS_KS_PCM_HEADERS 1
#include <initguid.h>
#include <objbase.h>
#include <winioctl.h>
#include <ks.h>
#include <ksmedia.h>
#include <mmreg.h>
#endif
#endif
#endif

namespace aptt {
namespace {

constexpr int kKsInvalidArgument = 0x41001;
constexpr int kKsInvalidState = 0x41002;
constexpr int kKsNotInitialized = 0x41003;
constexpr int kKsResetDisabled = 0x41004;
constexpr int kKsRenderThreadJoinTimeout = 0x41005;
constexpr int kKsNotImplemented =
    static_cast<int>(static_cast<std::int32_t>(0x80004001u));
constexpr std::uint32_t kKsRenderThreadJoinTimeoutMs = 5000;
constexpr char kKsRenderThreadJoinTimeoutSymbol[] =
    "APTT_KS_RENDER_THREAD_JOIN_TIMEOUT";
constexpr char kKsCancelThreadHandleUnavailableSymbol[] =
    "APTT_KS_CANCEL_THREAD_HANDLE_UNAVAILABLE";
constexpr char kKsRenderThreadJoinTimeoutMessage[] =
    "\x4B\x53\xE6\x9B\xB8\xE3\x81\x8D\xE8\xBE\xBC\xE3\x81\xBF"
    "\xE3\x82\xB9\xE3\x83\xAC\xE3\x83\x83\xE3\x83\x89\xE3\x81\xAE"
    "\xE7\xB5\x82\xE4\xBA\x86\xE5\xBE\x85\xE3\x81\xA1\xE3\x81\x8C"
    "\xE3\x82\xBF\xE3\x82\xA4\xE3\x83\xA0\xE3\x82\xA2\xE3\x82\xA6"
    "\xE3\x83\x88\xE3\x81\x97\xE3\x81\xBE\xE3\x81\x97\xE3\x81\x9F"
    "\xE3\x80\x82\xE3\x83\x87\xE3\x83\x90\xE3\x82\xA4\xE3\x82\xB9"
    "\xE3\x82\x92\xE5\xAE\x89\xE5\x85\xA8\xE3\x81\xAB\xE8\xA7\xA3"
    "\xE6\x94\xBE\xE3\x81\xA7\xE3\x81\x8D\xE3\x81\xA6\xE3\x81\x84"
    "\xE3\x81\xAA\xE3\x81\x84\xE5\x8F\xAF\xE8\x83\xBD\xE6\x80\xA7"
    "\xE3\x81\x8C\xE3\x81\x82\xE3\x82\x8A\xE3\x81\xBE\xE3\x81\x99"
    "\xE3\x80\x82";
constexpr char kKsRunningSilenceRestartRequiredMessage[] =
    "\x4B\x53\xE4\xBF\x9D\xE6\x8C\x81\xE4\xB8\xAD\xE3\x82\xB9"
    "\xE3\x83\x88\xE3\x83\xAA\xE3\x83\xBC\xE3\x83\xA0\xE3\x81\x8B"
    "\xE3\x82\x89\xE3\x81\xAE\xE5\x8D\xB3\xE6\x99\x82\xE4\xBF\xA1"
    "\xE5\x8F\xB7\xE5\x86\x8D\xE9\x96\x8B\xE3\x81\xAF\xE6\x9C\xAA"
    "\xE5\xAF\xBE\xE5\xBF\x9C\xE3\x81\xA7\xE3\x81\x99\xE3\x80\x82"
    "\xE4\xBF\x9D\xE6\x8C\x81\xE4\xB8\xAD\xE3\x83\x87\xE3\x83\x90"
    "\xE3\x82\xA4\xE3\x82\xB9\xE3\x82\x92\xE8\xA7\xA3\xE6\x94\xBE"
    "\xE3\x81\x97\xE3\x81\xA6\xE3\x81\x8B\xE3\x82\x89\xE5\x86\x8D"
    "\xE5\xAE\x9F\xE8\xA1\x8C\xE3\x81\x97\xE3\x81\xA6\xE3\x81\x8F"
    "\xE3\x81\xA0\xE3\x81\x95\xE3\x81\x84\xE3\x80\x82";
constexpr std::uint32_t kKsWaveRtNotificationCount = 2;

enum class KernelStreamingPlaybackPath {
  kStandardPacket,
  kWaveRtCyclic,
};

const char* KernelStreamingModelName(KernelStreamingPlaybackPath path) {
  switch (path) {
    case KernelStreamingPlaybackPath::kWaveRtCyclic:
      return "wavert_cyclic";
    case KernelStreamingPlaybackPath::kStandardPacket:
      return "standard_packet";
  }
  return "unknown";
}

const char* KernelStreamingPlaybackPathLabelJa(
    KernelStreamingPlaybackPath path) {
  switch (path) {
    case KernelStreamingPlaybackPath::kWaveRtCyclic:
      return "WaveRT\xE5\xBE\xAA\xE7\x92\xB0\xE3\x83\x90\xE3\x83\x83"
             "\xE3\x83\x95\xE3\x82\xA1";
    case KernelStreamingPlaybackPath::kStandardPacket:
      return "\x4B\x53\xE6\xA8\x99\xE6\xBA\x96\xE3\x83\x91\xE3\x82"
             "\xB1\xE3\x83\x83\xE3\x83\x88";
  }
  return "\xE6\x9C\xAA\xE7\xA2\xBA\xE8\xAA\x8D";
}

const char* KernelStreamingRuntimeApi(KernelStreamingPlaybackPath path) {
  switch (path) {
    case KernelStreamingPlaybackPath::kWaveRtCyclic:
      return "WaveRT cyclic buffer memory write";
    case KernelStreamingPlaybackPath::kStandardPacket:
      return "DeviceIoControl(IOCTL_KS_WRITE_STREAM)";
  }
  return "Kernel Streaming";
}

std::string CodeHex(int code) {
  return HexCode(static_cast<std::int64_t>(code));
}

std::string CodeHexForDomain(int code, std::string_view code_domain) {
  return HexCode32ForDomain(static_cast<std::int64_t>(code), code_domain);
}

const char* Win32Symbol(int code) {
#if defined(_WIN32)
  switch (static_cast<DWORD>(code)) {
    case ERROR_SUCCESS:
      return "ERROR_SUCCESS";
    case ERROR_NOT_FOUND:
      return "ERROR_NOT_FOUND";
    case ERROR_MOD_NOT_FOUND:
      return "ERROR_MOD_NOT_FOUND";
    case ERROR_PROC_NOT_FOUND:
      return "ERROR_PROC_NOT_FOUND";
    case ERROR_FILE_NOT_FOUND:
      return "ERROR_FILE_NOT_FOUND";
    case ERROR_PATH_NOT_FOUND:
      return "ERROR_PATH_NOT_FOUND";
    case ERROR_ACCESS_DENIED:
      return "ERROR_ACCESS_DENIED";
    case ERROR_DEVICE_NOT_CONNECTED:
      return "ERROR_DEVICE_NOT_CONNECTED";
    case ERROR_INVALID_HANDLE:
      return "ERROR_INVALID_HANDLE";
    case ERROR_INVALID_PARAMETER:
      return "ERROR_INVALID_PARAMETER";
    case ERROR_NO_MATCH:
      return "ERROR_NO_MATCH";
    default:
      return "WIN32_ERROR";
  }
#else
  (void)code;
  return "WIN32_ERROR";
#endif
}

bool LooksLikeKernelStreamingStableId(const std::string& stable_id) {
  return ParseKernelStreamingStableId(stable_id).has_value();
}

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(64);
  config.channel_count = format.channels.channel_count;
  config.marker_starts_with_0x05 = format.dop_marker_starts_with_0x05;
  config.dsd_byte_order = SampleType::kDsd1BitLsbFirst;
  return config;
}

const char* KeepAliveFormatName(const FormatDescriptor& format) {
  return IsDopMode(format) ? "valid-dop-silence" : "valid-pcm-silence";
}

OperationResult ValidateConfigForPlayback(const PlaybackConfig& config) {
  if (config.backend != BackendApi::kKernelStreaming) {
    return OperationResult::Failure(
        kKsInvalidArgument,
        "Kernel Streaming PCM playback requires BackendApi::kKernelStreaming");
  }
  if (!LooksLikeKernelStreamingStableId(config.device.stable_id)) {
    return OperationResult::Failure(
        kKsInvalidArgument,
        "Kernel Streaming PCM playback requires ks:<filter>#pin:<id>");
  }
  if (!IsKernelStreamingPlaybackFormat(config.format)) {
    return OperationResult::Failure(
        kKsInvalidArgument,
        "Kernel Streaming playback requires a renderable PCM format or explicit DoP carrier");
  }
  if (IsDopMode(config.format)) {
    if (config.frequency_hz <= 0.0) {
      return OperationResult::Failure(
          kKsInvalidArgument,
          "Kernel Streaming DoP playback requires a positive signal frequency");
    }
    if (config.amplitude_dbfs > 0.0) {
      return OperationResult::Failure(
          kKsInvalidArgument,
          "Kernel Streaming DoP playback requires amplitude <= 0 dBFS");
    }
  }
  if (config.format.sample_rate_hz == 0 ||
      config.format.channels.channel_count == 0) {
    return OperationResult::Failure(
        kKsInvalidArgument,
        "Kernel Streaming PCM playback requires non-zero rate and channels");
  }
  return OperationResult::Success();
}

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);
}

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();
}

#if defined(APTT_HAS_WINDOWS_KS_PCM_HEADERS)

std::int64_t Win32Code(DWORD result) {
  return static_cast<std::int64_t>(result);
}

std::int64_t NtStatusCode(LONG result) {
  return 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;
}

class ScopedHandle {
 public:
  ScopedHandle() = default;
  explicit ScopedHandle(HANDLE handle) : handle_(handle) {}
  ScopedHandle(const ScopedHandle&) = delete;
  ScopedHandle& operator=(const ScopedHandle&) = delete;
  ~ScopedHandle() { reset(); }

  HANDLE get() const { return handle_; }
  HANDLE* put() { return &handle_; }
  bool valid() const {
    return handle_ != nullptr && handle_ != INVALID_HANDLE_VALUE;
  }
  HANDLE release() {
    HANDLE value = handle_;
    handle_ = nullptr;
    return value;
  }
  void reset(HANDLE next = nullptr) {
    if (valid()) {
      CloseHandle(handle_);
    }
    handle_ = next;
  }

 private:
  HANDLE handle_ = nullptr;
};

bool IsFloatPcm(const FormatDescriptor& format) {
  return format.sample_type == SampleType::kFloat32;
}

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 = IsFloatPcm(descriptor) ? KSDATAFORMAT_SUBTYPE_IEEE_FLOAT
                                          : KSDATAFORMAT_SUBTYPE_PCM;
  return wave;
}

struct KsPinConnectWaveFormat {
  KSPIN_CONNECT connect;
  KSDATAFORMAT data_format;
  WAVEFORMATEXTENSIBLE wave_format;
};

struct KernelStreamingPinCreateResult {
  OperationResult result = OperationResult::Success();
  std::string api = "KsCreatePin";
  std::string code_domain = "ntstatus";
  std::string symbol = "STATUS_SUCCESS";
};

OperationResult SetKernelStreamingPinState(HANDLE pin,
                                           KSSTATE state,
                                           std::string_view label) {
  KSPROPERTY property{};
  property.Set = KSPROPSETID_Connection;
  property.Id = KSPROPERTY_CONNECTION_STATE;
  property.Flags = KSPROPERTY_TYPE_SET;
  DWORD returned = 0;
  const BOOL ok = DeviceIoControl(pin,
                                  IOCTL_KS_PROPERTY,
                                  &property,
                                  sizeof(property),
                                  &state,
                                  sizeof(state),
                                  &returned,
                                  nullptr);
  if (ok == FALSE) {
    std::ostringstream message;
    message << "Kernel Streaming state transition failed: " << label;
    return OperationResult::Failure(static_cast<int>(GetLastError()),
                                    message.str());
  }
  return OperationResult::Success();
}

template <typename T>
std::optional<T> QueryKernelStreamingPinProperty(HANDLE filter,
                                                 ULONG pin_id,
                                                 ULONG property_id) {
  KSP_PIN property{};
  property.Property.Set = KSPROPSETID_Pin;
  property.Property.Id = property_id;
  property.Property.Flags = KSPROPERTY_TYPE_GET;
  property.PinId = pin_id;
  T value{};
  DWORD returned = 0;
  const BOOL ok = DeviceIoControl(filter,
                                  IOCTL_KS_PROPERTY,
                                  &property,
                                  sizeof(property),
                                  &value,
                                  sizeof(value),
                                  &returned,
                                  nullptr);
  if (ok == FALSE) {
    return std::nullopt;
  }
  return value;
}

bool IsKernelStreamingRenderPlaybackPin(KSPIN_DATAFLOW dataflow,
                                        KSPIN_COMMUNICATION communication) {
  return dataflow == KSPIN_DATAFLOW_IN &&
         (communication == KSPIN_COMMUNICATION_SINK ||
          communication == KSPIN_COMMUNICATION_BOTH);
}

bool IsKernelStreamingStandardStreamingInterface(
    const KSPIN_INTERFACE& value) {
  return IsEqualGUID(value.Set, KSINTERFACESETID_Standard) &&
         value.Id == KSINTERFACE_STANDARD_STREAMING;
}

bool IsKernelStreamingLoopedStreamingInterface(
    const KSPIN_INTERFACE& value) {
  return IsEqualGUID(value.Set, KSINTERFACESETID_Standard) &&
         value.Id == KSINTERFACE_STANDARD_LOOPED_STREAMING;
}

template <typename T>
std::vector<T> QueryKernelStreamingPinPropertyArray(HANDLE filter,
                                                    ULONG pin_id,
                                                    ULONG property_id) {
  KSP_PIN property{};
  property.Property.Set = KSPROPSETID_Pin;
  property.Property.Id = property_id;
  property.Property.Flags = KSPROPERTY_TYPE_GET;
  property.PinId = pin_id;

  std::vector<std::byte> buffer(4096);
  DWORD returned = 0;
  const BOOL ok = DeviceIoControl(filter,
                                  IOCTL_KS_PROPERTY,
                                  &property,
                                  sizeof(property),
                                  buffer.data(),
                                  static_cast<DWORD>(buffer.size()),
                                  &returned,
                                  nullptr);
  if (ok == FALSE || returned < sizeof(KSMULTIPLE_ITEM)) {
    return {};
  }
  const auto* multiple =
      reinterpret_cast<const KSMULTIPLE_ITEM*>(buffer.data());
  const auto available_items =
      (returned - sizeof(KSMULTIPLE_ITEM)) / sizeof(T);
  const auto count = std::min<DWORD>(multiple->Count, available_items);
  const auto* first =
      reinterpret_cast<const T*>(buffer.data() + sizeof(KSMULTIPLE_ITEM));
  return std::vector<T>(first, first + count);
}

KSPIN_INTERFACE SelectKernelStreamingPinInterface(
    const std::vector<KSPIN_INTERFACE>& interfaces,
    bool prefer_looped) {
  if (prefer_looped) {
    const auto looped = std::find_if(
        interfaces.begin(),
        interfaces.end(),
        IsKernelStreamingLoopedStreamingInterface);
    if (looped != interfaces.end()) {
      return *looped;
    }
  }
  const auto streaming = std::find_if(
      interfaces.begin(),
      interfaces.end(),
      IsKernelStreamingStandardStreamingInterface);
  if (streaming != interfaces.end()) {
    return *streaming;
  }
  const auto looped = std::find_if(
      interfaces.begin(),
      interfaces.end(),
      IsKernelStreamingLoopedStreamingInterface);
  if (looped != interfaces.end()) {
    return *looped;
  }
  KSPIN_INTERFACE fallback{};
  fallback.Set = KSINTERFACESETID_Standard;
  fallback.Id = KSINTERFACE_STANDARD_STREAMING;
  return fallback;
}

KSPIN_MEDIUM SelectKernelStreamingPinMedium(
    const std::vector<KSPIN_MEDIUM>& mediums) {
  const auto standard = std::find_if(
      mediums.begin(),
      mediums.end(),
      [](const KSPIN_MEDIUM& value) {
        return IsEqualGUID(value.Set, KSMEDIUMSETID_Standard) &&
               value.Id == KSMEDIUM_STANDARD_DEVIO;
      });
  if (standard != mediums.end()) {
    return *standard;
  }
  if (!mediums.empty()) {
    return mediums.front();
  }
  KSPIN_MEDIUM fallback{};
  fallback.Set = KSMEDIUMSETID_Standard;
  fallback.Id = KSMEDIUM_STANDARD_DEVIO;
  return fallback;
}

std::string KernelStreamingInterfaceLabel(const KSPIN_INTERFACE& value) {
  if (IsEqualGUID(value.Set, KSINTERFACESETID_Standard)) {
    if (value.Id == KSINTERFACE_STANDARD_LOOPED_STREAMING) {
      return "KSINTERFACE_STANDARD_LOOPED_STREAMING";
    }
    if (value.Id == KSINTERFACE_STANDARD_STREAMING) {
      return "KSINTERFACE_STANDARD_STREAMING";
    }
    return "KSINTERFACESETID_Standard/" + std::to_string(value.Id);
  }
  return "custom/" + std::to_string(value.Id);
}

std::string KernelStreamingMediumLabel(const KSPIN_MEDIUM& value) {
  if (IsEqualGUID(value.Set, KSMEDIUMSETID_Standard)) {
    if (value.Id == KSMEDIUM_STANDARD_DEVIO) {
      return "KSMEDIUM_STANDARD_DEVIO";
    }
    return "KSMEDIUMSETID_Standard/" + std::to_string(value.Id);
  }
  return "custom/" + std::to_string(value.Id);
}

KernelStreamingPinCreateResult CreateKernelStreamingPin(
    const PlaybackConfig& config,
    HANDLE filter,
    std::uint32_t pin_id,
    const KSPIN_INTERFACE& pin_interface,
    const KSPIN_MEDIUM& pin_medium,
    HANDLE* pin_out) {
  KsPinConnectWaveFormat request{};
  request.connect.Interface = pin_interface;
  request.connect.Medium = pin_medium;
  request.connect.PinId = pin_id;
  request.connect.Priority.PriorityClass = KSPRIORITY_NORMAL;
  request.connect.Priority.PrioritySubClass = 1;
  request.data_format.FormatSize =
      sizeof(KSDATAFORMAT) + sizeof(WAVEFORMATEXTENSIBLE);
  request.data_format.SampleSize =
      (config.format.channels.channel_count *
       config.format.container_bits_per_sample) /
      8;
  request.data_format.MajorFormat = KSDATAFORMAT_TYPE_AUDIO;
  request.data_format.SubFormat = IsFloatPcm(config.format)
      ? KSDATAFORMAT_SUBTYPE_IEEE_FLOAT
      : KSDATAFORMAT_SUBTYPE_PCM;
  request.data_format.Specifier = KSDATAFORMAT_SPECIFIER_WAVEFORMATEX;
  request.wave_format = WaveFormatFromDescriptor(config.format);

  using KsCreatePinFn = DWORD(WINAPI*)(HANDLE, PKSPIN_CONNECT, ACCESS_MASK,
                                       PHANDLE);
  HMODULE ksuser = LoadLibraryW(L"ksuser.dll");
  if (ksuser == nullptr) {
    const int code = static_cast<int>(GetLastError());
    return KernelStreamingPinCreateResult{
        .result = OperationResult::Failure(code, "failed to load ksuser.dll"),
        .api = "LoadLibraryW(ksuser.dll)",
        .code_domain = "win32",
        .symbol = Win32Symbol(code),
    };
  }
  const auto create_pin = reinterpret_cast<KsCreatePinFn>(
      GetProcAddress(ksuser, "KsCreatePin"));
  if (create_pin == nullptr) {
    const DWORD last_error = GetLastError();
    FreeLibrary(ksuser);
    const int code = static_cast<int>(last_error);
    return KernelStreamingPinCreateResult{
        .result =
            OperationResult::Failure(code, "failed to resolve KsCreatePin"),
        .api = "GetProcAddress(KsCreatePin)",
        .code_domain = "win32",
        .symbol = Win32Symbol(code),
    };
  }

  HANDLE pin = nullptr;
  const DWORD status =
      create_pin(filter, &request.connect, GENERIC_READ | GENERIC_WRITE, &pin);
  FreeLibrary(ksuser);
  if (status != 0 || pin == nullptr || pin == INVALID_HANDLE_VALUE) {
    const int code = static_cast<int>(Win32Code(status));
    std::ostringstream message;
    message << "KsCreatePin failed for Kernel Streaming playback: "
            << Win32Symbol(code);
    return KernelStreamingPinCreateResult{
        .result = OperationResult::Failure(code, message.str()),
        .api = "KsCreatePin",
        .code_domain = "win32",
        .symbol = Win32Symbol(code),
    };
  }
  *pin_out = pin;
  return KernelStreamingPinCreateResult{};
}

struct KernelStreamingWaveRtBufferResult {
  OperationResult result = OperationResult::Success();
  KSRTAUDIO_BUFFER buffer{};
  std::string api = "DeviceIoControl(KSPROPERTY_RTAUDIO_BUFFER_WITH_NOTIFICATION)";
  std::string code_domain = "win32";
  std::string symbol = "ERROR_SUCCESS";
};

KernelStreamingWaveRtBufferResult AcquireKernelStreamingWaveRtBuffer(
    HANDLE pin,
    std::uint32_t requested_buffer_bytes) {
  KSRTAUDIO_BUFFER_PROPERTY_WITH_NOTIFICATION property{};
  property.Property.Set = KSPROPSETID_RtAudio;
  property.Property.Id = KSPROPERTY_RTAUDIO_BUFFER_WITH_NOTIFICATION;
  property.Property.Flags = KSPROPERTY_TYPE_GET;
  property.BaseAddress = nullptr;
  property.RequestedBufferSize = requested_buffer_bytes;
  property.NotificationCount = kKsWaveRtNotificationCount;

  KSRTAUDIO_BUFFER buffer{};
  DWORD returned = 0;
  const BOOL ok = DeviceIoControl(pin,
                                  IOCTL_KS_PROPERTY,
                                  &property,
                                  sizeof(property),
                                  &buffer,
                                  sizeof(buffer),
                                  &returned,
                                  nullptr);
  if (ok == FALSE || buffer.BufferAddress == nullptr ||
      buffer.ActualBufferSize == 0) {
    const int code = static_cast<int>(GetLastError());
    return KernelStreamingWaveRtBufferResult{
        .result = OperationResult::Failure(
            code,
            "KSPROPERTY_RTAUDIO_BUFFER_WITH_NOTIFICATION failed"),
        .buffer = {},
        .api = "DeviceIoControl(KSPROPERTY_RTAUDIO_BUFFER_WITH_NOTIFICATION)",
        .code_domain = "win32",
        .symbol = Win32Symbol(code),
    };
  }
  return KernelStreamingWaveRtBufferResult{
      .result = OperationResult::Success(),
      .buffer = buffer,
      .api = "DeviceIoControl(KSPROPERTY_RTAUDIO_BUFFER_WITH_NOTIFICATION)",
      .code_domain = "win32",
      .symbol = "ERROR_SUCCESS",
  };
}

OperationResult RegisterKernelStreamingWaveRtNotificationEvent(
    HANDLE pin,
    HANDLE notification_event) {
  KSRTAUDIO_NOTIFICATION_EVENT_PROPERTY property{};
  property.Property.Set = KSPROPSETID_RtAudio;
  property.Property.Id = KSPROPERTY_RTAUDIO_REGISTER_NOTIFICATION_EVENT;
  property.Property.Flags = KSPROPERTY_TYPE_SET;
  property.NotificationEvent = notification_event;
  DWORD returned = 0;
  const BOOL ok = DeviceIoControl(pin,
                                  IOCTL_KS_PROPERTY,
                                  &property,
                                  sizeof(property),
                                  nullptr,
                                  0,
                                  &returned,
                                  nullptr);
  if (ok == FALSE) {
    return OperationResult::Failure(
        static_cast<int>(GetLastError()),
        "KSPROPERTY_RTAUDIO_REGISTER_NOTIFICATION_EVENT failed");
  }
  return OperationResult::Success();
}

OperationResult UnregisterKernelStreamingWaveRtNotificationEvent(
    HANDLE pin,
    HANDLE notification_event) {
  KSRTAUDIO_NOTIFICATION_EVENT_PROPERTY property{};
  property.Property.Set = KSPROPSETID_RtAudio;
  property.Property.Id = KSPROPERTY_RTAUDIO_UNREGISTER_NOTIFICATION_EVENT;
  property.Property.Flags = KSPROPERTY_TYPE_SET;
  property.NotificationEvent = notification_event;
  DWORD returned = 0;
  const BOOL ok = DeviceIoControl(pin,
                                  IOCTL_KS_PROPERTY,
                                  &property,
                                  sizeof(property),
                                  nullptr,
                                  0,
                                  &returned,
                                  nullptr);
  if (ok == FALSE) {
    return OperationResult::Failure(
        static_cast<int>(GetLastError()),
        "KSPROPERTY_RTAUDIO_UNREGISTER_NOTIFICATION_EVENT failed");
  }
  return OperationResult::Success();
}

OperationResult WriteKernelStreamingPacket(HANDLE pin,
                                           const std::vector<std::uint8_t>& data,
                                           std::uint32_t frames,
                                           std::uint32_t sample_rate_hz) {
  KSSTREAM_HEADER header{};
  header.Size = sizeof(header);
  header.PresentationTime.Numerator = 1;
  header.PresentationTime.Denominator = 1;
  header.Duration =
      sample_rate_hz == 0
          ? 0
          : static_cast<LONGLONG>(
                (static_cast<std::uint64_t>(frames) * 10000000ULL) /
                sample_rate_hz);
  header.FrameExtent = static_cast<ULONG>(data.size());
  header.DataUsed = static_cast<ULONG>(data.size());
  header.Data = const_cast<std::uint8_t*>(data.data());
  header.OptionsFlags = KSSTREAM_HEADER_OPTIONSF_DURATIONVALID;

  DWORD returned = 0;
  const BOOL ok = DeviceIoControl(pin,
                                  IOCTL_KS_WRITE_STREAM,
                                  &header,
                                  sizeof(header),
                                  nullptr,
                                  0,
                                  &returned,
                                  nullptr);
  if (ok == FALSE) {
    return OperationResult::Failure(static_cast<int>(GetLastError()),
                                    "IOCTL_KS_WRITE_STREAM failed");
  }
  return OperationResult::Success();
}

#endif

}  // namespace

KernelStreamingPcmPolicy MakeKernelStreamingPcmPolicy(
    const PlaybackConfig& config) {
  KernelStreamingPcmPolicy policy;
  policy.keep_warm_after_signal =
      config.hold_mode == HoldMode::kKeepWarmAfterStop;
  policy.release_after_drain =
      config.hold_mode == HoldMode::kReleaseAfterDrain;
  policy.release_cooldown_ms = config.release_cooldown_ms == 0
                                   ? 1
                                   : config.release_cooldown_ms;
  return policy;
}

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

bool IsKernelStreamingDopCarrierFormat(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 ||
      format.channels.channel_count == 0) {
    return false;
  }
  if (!format.dsd_rate_multiplier ||
      !IsSupportedDopRate(*format.dsd_rate_multiplier)) {
    return false;
  }
  return format.sample_rate_hz ==
         DopCarrierSampleRateHz(*format.dsd_rate_multiplier);
}

bool IsKernelStreamingPlaybackFormat(const FormatDescriptor& format) {
  return IsKernelStreamingPcmPlaybackFormat(format) ||
         IsKernelStreamingDopCarrierFormat(format);
}

const char* KernelStreamingRunningSilenceRestartRequiredMessage() {
  return kKsRunningSilenceRestartRequiredMessage;
}

bool IsKernelStreamingConfirmedPlaybackProbe(
    const CapabilityProbeRecord& probe) {
  if (probe.kind != CapabilityProbeKind::kFormatSupport ||
      probe.support != CapabilitySupport::kSupported ||
      !probe.accepted_format) {
    return false;
  }
  const auto level = probe.backend_fields.find("ks_result_level");
  if (level == probe.backend_fields.end()) {
    return false;
  }
  return level->second == "pin_create_verified" ||
         level->second == "start_verified";
}

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

struct KernelStreamingPcmBackend::Impl {
  ~Impl() {
    FinalizeRenderThreadForDestruction();
    ReleaseHandles();
    CloseRenderThreadCancelHandle();
  }

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

  DeviceList EnumerateDevices() {
    DeviceList devices;
    const auto snapshot = EnumerateKernelStreamingDevices();
    devices.reserve(snapshot.devices.size());
    for (const auto& device_snapshot : snapshot.devices) {
      devices.push_back(device_snapshot.device);
    }
    return devices;
  }

  FormatProbeResult ProbeFormats(const DeviceInfo& device) {
    KernelStreamingFormatProbeRequest request;
    request.stable_id = device.stable_id;
    request.candidate_formats = KernelStreamingDefaultPcmCandidates();
    request.create_pin_for_exact_format = false;
    const auto snapshot = ProbeKernelStreamingPinFormats(request);

    FormatProbeResult result;
    result.requested = KernelStreamingPcmCandidate(
        48000,
        SampleType::kFloat32,
        2);
    for (const auto& probe : snapshot.probes) {
      if (probe.kind != CapabilityProbeKind::kFormatSupport) {
        continue;
      }
      if (probe.requested_format) {
        result.requested = *probe.requested_format;
      }
      if (IsKernelStreamingConfirmedPlaybackProbe(probe)) {
        result.supported_formats.push_back(*probe.accepted_format);
      } else if (probe.support == CapabilitySupport::kSupported &&
                 probe.accepted_format) {
        const auto level = probe.backend_fields.find("ks_result_level");
        std::ostringstream reason;
        reason << "Kernel Streaming format is candidate-only";
        if (level != probe.backend_fields.end()) {
          reason << " (" << level->second << ")";
        }
        reason << "; pin creation/start is not confirmed";
        result.rejection_reasons.push_back(reason.str());
      } else if (!probe.detail.empty()) {
        result.rejection_reasons.push_back(probe.detail);
      }
    }
    if (snapshot.discovery_error) {
      result.rejection_reasons.push_back(snapshot.discovery_error->message);
    }
    return result;
  }

  OperationResult Initialize(const PlaybackConfig& config) {
    auto validation = ValidateConfigForPlayback(config);
    if (!validation.ok) {
      return Fail(validation.error.code, validation.error.message);
    }
    if (GetState() != DeviceLifecycleState::kDiscovered &&
        GetState() != DeviceLifecycleState::kReleased) {
      return Fail(kKsInvalidState,
                  "Kernel Streaming backend must be released before reinitialize");
    }

    config_ = config;
    policy_ = MakeKernelStreamingPcmPolicy(config_);
    target_frames_ = DurationFrames(config_);
    packet_frames_ = std::max<std::uint32_t>(
        32,
        (config_.format.sample_rate_hz * policy_.packet_duration_ms) / 1000);
    bytes_per_frame_ =
        (config_.format.channels.channel_count *
         config_.format.container_bits_per_sample) /
        8;
    generator_.ResetPhase();
    dop_generator_.Reset();
    force_silence_ = false;
    render_thread_stop_ = false;
    render_thread_exited_ = true;
    signal_frames_written_ = 0;
    stats_ = {};
    stats_.expected_callback_interval_ms =
        (static_cast<double>(packet_frames_) * 1000.0) /
        static_cast<double>(config_.format.sample_rate_hz);

    if (!TransitionTo(DeviceLifecycleState::kReserved,
                      "selected Kernel Streaming filter/pin reserved")) {
      return OperationResult::Failure(kKsInvalidState, GetLastError().message);
    }

#if !defined(APTT_HAS_WINDOWS_KS_PCM_HEADERS)
    TransitionTo(DeviceLifecycleState::kFaulted,
                 "Kernel Streaming playback is not available");
    return Fail(kKsNotImplemented,
                "Kernel Streaming playback requires Windows KS headers");
#else
    const auto parsed = ParseKernelStreamingStableId(config_.device.stable_id);
    if (!parsed) {
      TransitionTo(DeviceLifecycleState::kFaulted,
                   "Kernel Streaming stable ID parse failed");
      return Fail(kKsInvalidArgument, "invalid Kernel Streaming stable ID");
    }
    ks_filter_path_ = parsed->filter_symbolic_link;
    ks_pin_id_ = parsed->pin_id;

    const std::wstring filter_path = Utf8ToWide(parsed->filter_symbolic_link);
    filter_handle_.reset(CreateFileW(filter_path.c_str(),
                                     GENERIC_READ | GENERIC_WRITE,
                                     FILE_SHARE_READ | FILE_SHARE_WRITE,
                                     nullptr,
                                     OPEN_EXISTING,
                                     FILE_ATTRIBUTE_NORMAL,
                                     nullptr));
    if (!filter_handle_.valid()) {
      const int code = static_cast<int>(::GetLastError());
      AddErrorEvent(code,
                    "CreateFileW",
                    "Kernel Streaming filter open failed",
                    "win32",
                    "initialize");
      TransitionTo(DeviceLifecycleState::kFaulted,
                   "Kernel Streaming filter open failed");
      return Fail(code, "failed to open Kernel Streaming filter");
    }

    const auto dataflow =
        QueryKernelStreamingPinProperty<KSPIN_DATAFLOW>(
            filter_handle_.get(),
            parsed->pin_id,
            KSPROPERTY_PIN_DATAFLOW);
    const auto communication =
        QueryKernelStreamingPinProperty<KSPIN_COMMUNICATION>(
            filter_handle_.get(),
            parsed->pin_id,
            KSPROPERTY_PIN_COMMUNICATION);
    if (!dataflow || !communication ||
        !IsKernelStreamingRenderPlaybackPin(*dataflow, *communication)) {
      AddErrorEvent(kKsInvalidArgument,
                    "KSPROPERTY_PIN_DATAFLOW/KSPROPERTY_PIN_COMMUNICATION",
                    "Kernel Streaming selected pin is not a render/sink playback pin",
                    "internal",
                    "initialize",
                    "APTT_KS_PIN_NOT_RENDER_PLAYBACK");
      TransitionTo(DeviceLifecycleState::kFaulted,
                   "Kernel Streaming selected pin is not playable");
      ReleaseHandles();
      return Fail(kKsInvalidArgument,
                  "Kernel Streaming selected pin is not a render/sink playback pin");
    }

    const auto pin_interfaces =
        QueryKernelStreamingPinPropertyArray<KSPIN_INTERFACE>(
            filter_handle_.get(),
            parsed->pin_id,
            KSPROPERTY_PIN_INTERFACES);
    const bool supports_standard_streaming =
        std::any_of(pin_interfaces.begin(),
                    pin_interfaces.end(),
                    IsKernelStreamingStandardStreamingInterface);
    const bool supports_looped_streaming =
        std::any_of(pin_interfaces.begin(),
                    pin_interfaces.end(),
                    IsKernelStreamingLoopedStreamingInterface);
    if (!supports_standard_streaming && !supports_looped_streaming) {
      AddErrorEvent(kKsInvalidArgument,
                    "KSPROPERTY_PIN_INTERFACES",
                    "Kernel Streaming selected pin exposes no implemented streaming interface",
                    "internal",
                    "initialize",
                    "APTT_KS_STREAMING_INTERFACE_UNIMPLEMENTED_FOR_PIN");
      TransitionTo(DeviceLifecycleState::kFaulted,
                   "Kernel Streaming playback found no implemented streaming interface");
      ReleaseHandles();
      return Fail(kKsInvalidArgument,
                  "Kernel Streaming playback found no implemented streaming interface");
    }
    const auto pin_mediums =
        QueryKernelStreamingPinPropertyArray<KSPIN_MEDIUM>(
            filter_handle_.get(),
            parsed->pin_id,
            KSPROPERTY_PIN_MEDIUMS);
    const auto pin_medium = SelectKernelStreamingPinMedium(pin_mediums);
    ks_medium_label_ = KernelStreamingMediumLabel(pin_medium);

    if (supports_looped_streaming) {
      const auto looped_interface =
          SelectKernelStreamingPinInterface(pin_interfaces, true);
      ks_interface_label_ = KernelStreamingInterfaceLabel(looped_interface);
      HANDLE raw_looped_pin = nullptr;
      auto pin_result = CreateKernelStreamingPin(config_,
                                                 filter_handle_.get(),
                                                 parsed->pin_id,
                                                 looped_interface,
                                                 pin_medium,
                                                 &raw_looped_pin);
      if (pin_result.result.ok) {
        pin_handle_.reset(raw_looped_pin);
        const auto requested_buffer_bytes = RequestedWaveRtBufferBytes();
        auto wavert_buffer = AcquireKernelStreamingWaveRtBuffer(
            pin_handle_.get(),
            requested_buffer_bytes);
        if (wavert_buffer.result.ok) {
          playback_path_ = KernelStreamingPlaybackPath::kWaveRtCyclic;
          wavert_buffer_address_ = wavert_buffer.buffer.BufferAddress;
          wavert_buffer_bytes_ = wavert_buffer.buffer.ActualBufferSize;
          wavert_call_memory_barrier_ =
              wavert_buffer.buffer.CallMemoryBarrier != FALSE;
          wavert_period_bytes_ =
              std::max<std::uint32_t>(
                  bytes_per_frame_,
                  wavert_buffer_bytes_ / kKsWaveRtNotificationCount);
          wavert_period_bytes_ -= wavert_period_bytes_ % bytes_per_frame_;
          wavert_period_frames_ = wavert_period_bytes_ / bytes_per_frame_;
          wavert_notification_event_.reset(
              CreateEventW(nullptr, FALSE, FALSE, nullptr));
          if (wavert_notification_event_.valid()) {
            auto register_result =
                RegisterKernelStreamingWaveRtNotificationEvent(
                    pin_handle_.get(),
                    wavert_notification_event_.get());
            AddWaveRtNotificationEvent("register", register_result);
            wavert_notification_registered_ = register_result.ok;
          } else {
            const int code = static_cast<int>(::GetLastError());
            AddErrorEvent(code,
                          "CreateEventW",
                          "Kernel Streaming WaveRT notification event creation failed",
                          "win32",
                          "initialize",
                          Win32Symbol(code));
          }
        } else {
          AddErrorEvent(wavert_buffer.result.error.code,
                        wavert_buffer.api,
                        "Kernel Streaming WaveRT cyclic buffer acquisition failed",
                        wavert_buffer.code_domain,
                        "initialize",
                        wavert_buffer.symbol);
          pin_handle_.reset();
        }
      } else if (!supports_standard_streaming) {
        AddErrorEvent(pin_result.result.error.code,
                      pin_result.api,
                      "Kernel Streaming looped pin creation failed",
                      pin_result.code_domain,
                      "initialize",
                      pin_result.symbol);
      }
    }

    if (!pin_handle_.valid() && supports_standard_streaming) {
      const auto standard_interface =
          SelectKernelStreamingPinInterface(pin_interfaces, false);
      ks_interface_label_ = KernelStreamingInterfaceLabel(standard_interface);
      HANDLE raw_pin = nullptr;
      auto pin_result = CreateKernelStreamingPin(config_,
                                                 filter_handle_.get(),
                                                 parsed->pin_id,
                                                 standard_interface,
                                                 pin_medium,
                                                 &raw_pin);
      if (!pin_result.result.ok) {
        AddErrorEvent(pin_result.result.error.code,
                      pin_result.api,
                      "Kernel Streaming pin creation failed",
                      pin_result.code_domain,
                      "initialize",
                      pin_result.symbol);
        TransitionTo(DeviceLifecycleState::kFaulted,
                     "Kernel Streaming pin creation failed");
        ReleaseHandles();
        return Fail(pin_result.result.error.code,
                    pin_result.result.error.message);
      }
      playback_path_ = KernelStreamingPlaybackPath::kStandardPacket;
      pin_handle_.reset(raw_pin);
    }

    if (!pin_handle_.valid()) {
      AddErrorEvent(kKsNotImplemented,
                    "KSPROPERTY_RTAUDIO_BUFFER_WITH_NOTIFICATION",
                    "Kernel Streaming looped/WaveRT playback could not be prepared",
                    "internal",
                    "initialize",
                    "APTT_KS_LOOPED_WAVERT_PREPARE_FAILED");
      TransitionTo(DeviceLifecycleState::kFaulted,
                   "Kernel Streaming looped/WaveRT playback could not be prepared");
      ReleaseHandles();
      return Fail(kKsNotImplemented,
                  "Kernel Streaming looped/WaveRT playback could not be prepared");
    }

    for (const auto state_step :
         {std::pair{KSSTATE_ACQUIRE, "ACQUIRE"},
          std::pair{KSSTATE_PAUSE, "PAUSE"}}) {
      auto state_result =
          SetKernelStreamingPinState(pin_handle_.get(),
                                     state_step.first,
                                     state_step.second);
      AddStateEvent(state_step.second, state_result);
      if (!state_result.ok) {
        TransitionTo(DeviceLifecycleState::kFaulted,
                     "Kernel Streaming pin state preparation failed");
        ReleaseHandles();
        return Fail(state_result.error.code, state_result.error.message);
      }
    }

    if (!TransitionTo(DeviceLifecycleState::kPrepared,
                      "Kernel Streaming pin prepared in PAUSE")) {
      ReleaseHandles();
      return OperationResult::Failure(kKsInvalidState, GetLastError().message);
    }
    AddInitializationEvent();
    return OperationResult::Success();
#endif
  }

  OperationResult Start() {
#if !defined(APTT_HAS_WINDOWS_KS_PCM_HEADERS)
    return Fail(kKsNotImplemented,
                "Kernel Streaming playback requires Windows KS headers");
#else
    const auto current = GetState();
    if (current == DeviceLifecycleState::kRunningSilence &&
        render_thread_.joinable()) {
      return Fail(kKsInvalidState,
                  kKsRunningSilenceRestartRequiredMessage);
    }
    if (current != DeviceLifecycleState::kPrepared &&
        current != DeviceLifecycleState::kHeldOpen) {
      return Fail(kKsInvalidState,
                  "Kernel Streaming pin must be prepared before start");
    }
    if (!pin_handle_.valid()) {
      return Fail(kKsNotInitialized, "Kernel Streaming pin is not initialized");
    }

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

    if (playback_path_ == KernelStreamingPlaybackPath::kWaveRtCyclic) {
      auto prime_result = PrimeWaveRtCyclicBuffer();
      if (!prime_result.ok) {
        AddErrorEvent(prime_result.error.code,
                      "WaveRT cyclic buffer prime",
                      prime_result.error.message,
                      "internal",
                      "initialize");
        TransitionTo(DeviceLifecycleState::kFaulted,
                     "Kernel Streaming WaveRT cyclic buffer prime failed");
        return Fail(prime_result.error.code, prime_result.error.message);
      }
    }

    auto run_result =
        SetKernelStreamingPinState(pin_handle_.get(), KSSTATE_RUN, "RUN");
    AddStateEvent("RUN", run_result);
    if (!run_result.ok) {
      TransitionTo(DeviceLifecycleState::kFaulted,
                   "Kernel Streaming RUN transition failed");
      return Fail(run_result.error.code, run_result.error.message);
    }

    const std::string start_message = IsDopMode(config_.format)
        ? "Kernel Streaming DoP 1 kHz DSD signal started"
        : "Kernel Streaming 1 kHz PCM signal started";
    if (!TransitionTo(DeviceLifecycleState::kRunningSignal,
                      start_message)) {
      return OperationResult::Failure(kKsInvalidState, GetLastError().message);
    }
    CloseRenderThreadCancelHandle();
    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;
      const std::string stop_message = IsDopMode(config_.format)
          ? "normal Kernel Streaming stop switched to valid DoP silence"
          : "normal Kernel Streaming stop switched to valid PCM silence";
      if (!TransitionTo(DeviceLifecycleState::kRunningSilence,
                        stop_message)) {
        return OperationResult::Failure(kKsInvalidState, 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,
                        "Kernel Streaming render thread draining before hold")) {
        return OperationResult::Failure(kKsInvalidState, GetLastError().message);
      }
      render_thread_stop_ = true;
      if (!JoinRenderThreadBounded("stop")) {
        return OperationResult::Failure(kKsRenderThreadJoinTimeout,
                                        kKsRenderThreadJoinTimeoutMessage);
      }
    }

    if (policy_.release_after_drain) {
      return Shutdown();
    }
    return PauseAndHold();
  }

  OperationResult Reset() {
    return Fail(kKsResetDisabled,
                "Kernel Streaming normal reset is disabled; use stop/hold/release");
  }

  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();
    const BackendError original_error = GetLastError();
    if (current == DeviceLifecycleState::kDiscovered ||
        current == DeviceLifecycleState::kReleased) {
      return OperationResult::Success();
    }
    if (current == DeviceLifecycleState::kFaulted) {
      AddReleaseEvent("Kernel Streaming faulted backend release requested",
                      original_error);
    }
    if (current == DeviceLifecycleState::kRunningSignal ||
        current == DeviceLifecycleState::kRunningSilence) {
      if (!TransitionTo(DeviceLifecycleState::kDraining,
                        "Kernel Streaming render thread draining before release")) {
        return OperationResult::Failure(kKsInvalidState, GetLastError().message);
      }
    }
    render_thread_stop_ = true;
    if (!JoinRenderThreadBounded("release")) {
      return OperationResult::Failure(kKsRenderThreadJoinTimeout,
                                      kKsRenderThreadJoinTimeoutMessage);
    }
    if (GetState() != DeviceLifecycleState::kFaulted) {
      TransitionTo(DeviceLifecycleState::kReleasing,
                   "Kernel Streaming pin entering explicit release");
    } else {
      AddReleaseEvent(
          "Kernel Streaming faulted backend closing handles before force release",
          original_error);
    }
#if defined(APTT_HAS_WINDOWS_KS_PCM_HEADERS)
    if (pin_handle_.valid()) {
      for (const auto state_step :
           {std::pair{KSSTATE_PAUSE, "PAUSE"},
            std::pair{KSSTATE_ACQUIRE, "ACQUIRE"},
            std::pair{KSSTATE_STOP, "STOP"}}) {
        auto state_result =
            SetKernelStreamingPinState(pin_handle_.get(),
                                       state_step.first,
                                       state_step.second);
        AddStateEvent(state_step.second, state_result);
        if (!state_result.ok && GetState() != DeviceLifecycleState::kFaulted) {
          TransitionTo(DeviceLifecycleState::kFaulted,
                       "Kernel Streaming release state transition failed");
          break;
        }
      }
    }
#endif
    ReleaseHandles();
    if (policy_.release_cooldown_ms > 0) {
      std::this_thread::sleep_for(
          std::chrono::milliseconds(policy_.release_cooldown_ms));
    }
    if (GetState() != DeviceLifecycleState::kFaulted) {
      TransitionTo(DeviceLifecycleState::kReleased,
                   "Kernel Streaming filter and pin released after cooldown");
      return OperationResult::Success();
    }
    if (!HandlesOpen()) {
      AddReleaseEvent(
          "Kernel Streaming faulted backend force-released after handles closed",
          original_error);
      if (TransitionTo(
              DeviceLifecycleState::kReleased,
              "Kernel Streaming faulted backend force-released after handles closed")) {
        if (!original_error.message.empty()) {
          SetLastError(original_error);
        }
        return OperationResult::Success();
      }
    }
    return OperationResult::Failure(kKsInvalidState, GetLastError().message);
  }

  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({kKsInvalidState, decision.reason});
        return false;
      }
      state_ = next;
    }

    auto event = MakeLifecycleEvent(
        NextSequence(),
        BackendApi::kKernelStreaming,
        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["ks_filter_symbolic_link"] = ks_filter_path_;
    event.backend_fields["ks_pin_id"] = std::to_string(ks_pin_id_);
    AppendEvent(std::move(event));
    SetLastError({});
    return true;
  }

  std::uint64_t NextSequence() { return sequence_.Next(); }

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

  void AddInitializationEvent() {
    DiagnosticEvent event;
    event.type = DiagnosticEventType::kFormatProbe;
    event.sequence = NextSequence();
    event.backend = BackendApi::kKernelStreaming;
    event.device_id = config_.device.stable_id;
    event.format = config_.format;
    event.message = IsDopMode(config_.format)
        ? "Kernel Streaming DoP carrier pin created and prepared"
        : "Kernel Streaming PCM pin created and prepared";
    event.backend_fields["requested_format"] = FormatSummary(config_.format);
    event.backend_fields["accepted_format"] = FormatSummary(config_.format);
    event.backend_fields["event_category"] = "initialize";
    event.backend_fields["api"] = "KsCreatePin";
    event.backend_fields["requested_access"] =
        "filter=GENERIC_READ|GENERIC_WRITE; pin=GENERIC_READ|GENERIC_WRITE";
    event.backend_fields["ks_pin_interface"] = ks_interface_label_;
    event.backend_fields["ks_pin_medium"] = ks_medium_label_;
    event.backend_fields["ks_streaming_model"] =
        KernelStreamingModelName(playback_path_);
    event.backend_fields["ks_playback_path"] =
        KernelStreamingPlaybackPathLabelJa(playback_path_);
    event.backend_fields["ks_playback_implementation"] = "implemented";
    event.backend_fields["wavert_buffer_bytes"] =
        std::to_string(wavert_buffer_bytes_);
    event.backend_fields["wavert_period_bytes"] =
        std::to_string(wavert_period_bytes_);
    event.backend_fields["wavert_period_frames"] =
        std::to_string(wavert_period_frames_);
    event.backend_fields["wavert_notification_count"] =
        std::to_string(kKsWaveRtNotificationCount);
    event.backend_fields["wavert_notification_registered"] =
        wavert_notification_registered_ ? "true" : "false";
    event.backend_fields["wavert_call_memory_barrier"] =
        wavert_call_memory_barrier_ ? "true" : "false";
    event.backend_fields["signal_mode"] = ToString(config_.format.signal_mode);
    event.backend_fields["keep_alive_format"] =
        KeepAliveFormatName(config_.format);
    event.backend_fields["ks_filter_symbolic_link"] = ks_filter_path_;
    event.backend_fields["ks_pin_id"] = std::to_string(ks_pin_id_);
    event.backend_fields["packet_duration_ms"] =
        std::to_string(policy_.packet_duration_ms);
    event.backend_fields["packet_frames"] = std::to_string(packet_frames_);
    event.backend_fields["bytes_per_frame"] = std::to_string(bytes_per_frame_);
    event.backend_fields["target_frames"] = std::to_string(target_frames_);
    event.backend_fields["keep_warm_after_signal"] =
        policy_.keep_warm_after_signal ? "true" : "false";
    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);
    if (IsDopMode(config_.format)) {
      event.backend_fields["dop_dsd_rate_multiplier"] =
          std::to_string(config_.format.dsd_rate_multiplier.value_or(0));
      event.backend_fields["dop_marker_first"] =
          config_.format.dop_marker_starts_with_0x05 ? "0x05" : "0xFA";
      event.backend_fields["dop_dsd_byte_order"] = "lsb-first";
      event.backend_fields["exact_carrier_required"] = "true";
    }
    AppendEvent(std::move(event));
  }

  void AddStateEvent(std::string state_label,
                     const OperationResult& result) {
    DiagnosticEvent event;
    event.type = result.ok ? DiagnosticEventType::kRuntimeStats
                           : DiagnosticEventType::kError;
    event.sequence = NextSequence();
    event.backend = BackendApi::kKernelStreaming;
    event.device_id = config_.device.stable_id;
    event.message = result.ok
        ? "Kernel Streaming pin state set to " + state_label
        : "Kernel Streaming pin state transition failed";
    event.backend_fields["api"] =
        "DeviceIoControl(KSPROPERTY_CONNECTION_STATE)";
    event.backend_fields["requested_ks_state"] = state_label;
    event.backend_fields["ks_state"] = std::move(state_label);
    event.backend_fields["code"] = std::to_string(result.error.code);
    event.backend_fields["code_signed"] = std::to_string(result.error.code);
    event.backend_fields["code_hex"] =
        CodeHexForDomain(result.error.code,
                         result.ok ? "unknown" : "win32");
    event.backend_fields["code_domain"] = result.ok ? "unknown" : "win32";
    event.backend_fields["symbol"] =
        result.ok ? "STATUS_SUCCESS" : Win32Symbol(result.error.code);
    AddCommonKernelStreamingEvidence(event, "state_transition");
    AppendEvent(std::move(event));
  }

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

  void AddWaveRtNotificationEvent(std::string action,
                                  const OperationResult& result) {
    DiagnosticEvent event;
    event.type = result.ok ? DiagnosticEventType::kRuntimeStats
                           : DiagnosticEventType::kError;
    event.sequence = NextSequence();
    event.backend = BackendApi::kKernelStreaming;
    event.device_id = config_.device.stable_id;
    event.message = result.ok
        ? "Kernel Streaming WaveRT notification event " + action + " succeeded"
        : "Kernel Streaming WaveRT notification event " + action + " failed";
    event.backend_fields["api"] =
        action == "register"
            ? "DeviceIoControl(KSPROPERTY_RTAUDIO_REGISTER_NOTIFICATION_EVENT)"
            : "DeviceIoControl(KSPROPERTY_RTAUDIO_UNREGISTER_NOTIFICATION_EVENT)";
    event.backend_fields["wavert_notification_action"] = std::move(action);
    event.backend_fields["code"] = std::to_string(result.error.code);
    event.backend_fields["code_signed"] = std::to_string(result.error.code);
    event.backend_fields["code_hex"] =
        CodeHexForDomain(result.error.code, result.ok ? "unknown" : "win32");
    event.backend_fields["code_domain"] = result.ok ? "unknown" : "win32";
    event.backend_fields["symbol"] =
        result.ok ? "ERROR_SUCCESS" : Win32Symbol(result.error.code);
    AddCommonKernelStreamingEvidence(
        event,
        action == "register" ? std::string_view("initialize")
                             : std::string_view("release"));
    AppendEvent(std::move(event));
  }

  void AddRuntimeEvent(double write_duration_ms,
                       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::kKernelStreaming;
    event.device_id = config_.device.stable_id;
    event.message = playback_path_ == KernelStreamingPlaybackPath::kWaveRtCyclic
        ? "Kernel Streaming WaveRT cyclic buffer write"
        : "Kernel Streaming standard packet write";
    event.realtime_stats = stats;
    event.backend_fields["api"] = KernelStreamingRuntimeApi(playback_path_);
    event.backend_fields["event_category"] = "stream_write";
    event.backend_fields["ks_streaming_model"] =
        KernelStreamingModelName(playback_path_);
    event.backend_fields["ks_playback_path"] =
        KernelStreamingPlaybackPathLabelJa(playback_path_);
    event.backend_fields["write_duration_ms"] =
        std::to_string(write_duration_ms);
    event.backend_fields["submitted_frames"] =
        std::to_string(submitted_frames);
    event.backend_fields["packet_bytes"] =
        std::to_string(static_cast<std::uint64_t>(submitted_frames) *
                       bytes_per_frame_);
    event.backend_fields["signal_mode"] = ToString(config_.format.signal_mode);
    event.backend_fields["keep_alive_format"] =
        KeepAliveFormatName(config_.format);
    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["dop_next_frame_index"] =
          std::to_string(dop_generator_.next_dop_frame_index());
    }
    AppendEvent(std::move(event));
  }

  void AddCommonKernelStreamingEvidence(DiagnosticEvent& event,
                                        std::string_view event_category) const {
    event.backend_fields["event_category"] = std::string(event_category);
    event.backend_fields["filter_symbolic_link"] = ks_filter_path_;
    event.backend_fields["ks_filter_symbolic_link"] = ks_filter_path_;
    event.backend_fields["pin_id"] = std::to_string(ks_pin_id_);
    event.backend_fields["ks_pin_id"] = std::to_string(ks_pin_id_);
    event.backend_fields["requested_format"] = FormatSummary(config_.format);
    event.backend_fields["packet_frames"] = std::to_string(packet_frames_);
    event.backend_fields["ks_streaming_model"] =
        KernelStreamingModelName(playback_path_);
    event.backend_fields["ks_playback_path"] =
        KernelStreamingPlaybackPathLabelJa(playback_path_);
  }

  void AddErrorEvent(int code,
                     std::string api,
                     std::string message,
                     std::string code_domain = "unknown",
                     std::string event_category = "stream_write",
                     std::string symbol = {}) {
    DiagnosticEvent event;
    event.type = DiagnosticEventType::kError;
    event.sequence = NextSequence();
    event.backend = BackendApi::kKernelStreaming;
    event.device_id = config_.device.stable_id;
    event.message = std::move(message);
    event.backend_fields["api"] = std::move(api);
    event.backend_fields["code"] = std::to_string(code);
    event.backend_fields["code_signed"] = std::to_string(code);
    event.backend_fields["code_hex"] =
        CodeHexForDomain(code, code_domain);
    event.backend_fields["code_domain"] = std::move(code_domain);
    if (!symbol.empty()) {
      event.backend_fields["symbol"] = std::move(symbol);
    } else if (event.backend_fields["code_domain"] == "win32") {
      event.backend_fields["symbol"] = Win32Symbol(code);
    } else if (event.backend_fields["code_domain"] == "ntstatus") {
      event.backend_fields["symbol"] = KernelStreamingStatusSymbol(code);
    } else {
      event.backend_fields["symbol"] = "unknown";
    }
    AddCommonKernelStreamingEvidence(event, event_category);
    AppendEvent(std::move(event));
  }

  void AddReleaseEvent(std::string message,
                       const BackendError& original_error) {
    DiagnosticEvent event;
    event.type = DiagnosticEventType::kRuntimeStats;
    event.sequence = NextSequence();
    event.backend = BackendApi::kKernelStreaming;
    event.device_id = config_.device.stable_id;
    event.message = std::move(message);
    event.backend_fields["api"] = "KernelStreamingPcmBackend::Shutdown";
    AddCommonKernelStreamingEvidence(event, "release");
    event.backend_fields["handles_open_after_release"] =
        HandlesOpen() ? "true" : "false";
    if (!original_error.message.empty()) {
      event.backend_fields["original_fault_code_signed"] =
          std::to_string(original_error.code);
      event.backend_fields["original_fault_code_hex"] =
          CodeHex(original_error.code);
      event.backend_fields["original_fault_message"] =
          original_error.message;
    }
    AppendEvent(std::move(event));
  }

  OperationResult PauseAndHold() {
#if defined(APTT_HAS_WINDOWS_KS_PCM_HEADERS)
    if (pin_handle_.valid()) {
      auto pause_result =
          SetKernelStreamingPinState(pin_handle_.get(), KSSTATE_PAUSE, "PAUSE");
      AddStateEvent("PAUSE", pause_result);
      if (!pause_result.ok) {
        TransitionTo(DeviceLifecycleState::kFaulted,
                     "Kernel Streaming PAUSE transition failed during hold");
        return Fail(pause_result.error.code, pause_result.error.message);
      }
    }
#endif
    if (GetState() != DeviceLifecycleState::kHeldOpen) {
      if (!TransitionTo(DeviceLifecycleState::kHeldOpen,
                        "Kernel Streaming pin held open after signal stop")) {
        return OperationResult::Failure(kKsInvalidState, GetLastError().message);
      }
    }
    return OperationResult::Success();
  }

  bool JoinRenderThreadBounded(std::string_view reason) {
    if (!render_thread_.joinable()) {
      return true;
    }
    RequestRenderThreadCancellation(reason);
    const auto deadline = std::chrono::steady_clock::now() +
                          std::chrono::milliseconds(
                              kKsRenderThreadJoinTimeoutMs);
    while (!render_thread_exited_.load(std::memory_order_acquire)) {
      if (std::chrono::steady_clock::now() >= deadline) {
        AddRenderThreadJoinTimeoutEvent(reason);
        TransitionTo(DeviceLifecycleState::kFaulted,
                     kKsRenderThreadJoinTimeoutMessage);
        SetLastError(
            {kKsRenderThreadJoinTimeout, kKsRenderThreadJoinTimeoutMessage});
        return false;
      }
      std::this_thread::sleep_for(std::chrono::milliseconds(20));
    }
    render_thread_.join();
    CloseRenderThreadCancelHandle();
    return true;
  }

  void RegisterRenderThreadCancelHandle() {
#if defined(_WIN32)
    HANDLE duplicated_thread = nullptr;
    const BOOL duplicated = DuplicateHandle(GetCurrentProcess(),
                                            GetCurrentThread(),
                                            GetCurrentProcess(),
                                            &duplicated_thread,
                                            0,
                                            FALSE,
                                            DUPLICATE_SAME_ACCESS);
    if (duplicated == 0) {
      const int code = static_cast<int>(::GetLastError());
      CloseRenderThreadCancelHandle();
      AddRenderThreadCancelHandleEvent(false, code, Win32Symbol(code));
      return;
    }

    HANDLE old_handle = nullptr;
    {
      std::lock_guard lock(render_thread_cancel_handle_mutex_);
      old_handle = render_thread_cancel_handle_;
      render_thread_cancel_handle_ = duplicated_thread;
    }
    if (old_handle != nullptr) {
      CloseHandle(old_handle);
    }
    AddRenderThreadCancelHandleEvent(true, 0, "ERROR_SUCCESS");
#endif
  }

  void CloseRenderThreadCancelHandle() {
#if defined(_WIN32)
    HANDLE handle = nullptr;
    {
      std::lock_guard lock(render_thread_cancel_handle_mutex_);
      handle = render_thread_cancel_handle_;
      render_thread_cancel_handle_ = nullptr;
    }
    if (handle != nullptr) {
      CloseHandle(handle);
    }
#endif
  }

  void RequestRenderThreadCancellation(std::string_view reason) {
#if defined(_WIN32)
    if (wavert_notification_event_.valid()) {
      SetEvent(wavert_notification_event_.get());
    }
    bool attempted = false;
    bool succeeded = false;
    int code = 0;
    const char* symbol = kKsCancelThreadHandleUnavailableSymbol;
    if (render_thread_.joinable()) {
      HANDLE cancel_handle = nullptr;
      {
        std::lock_guard lock(render_thread_cancel_handle_mutex_);
        cancel_handle = render_thread_cancel_handle_;
      }
      if (cancel_handle != nullptr) {
        attempted = true;
        if (CancelSynchronousIo(cancel_handle) != 0) {
          succeeded = true;
          symbol = "ERROR_SUCCESS";
        } else {
          code = static_cast<int>(::GetLastError());
          symbol = Win32Symbol(code);
        }
      }
    }
    AddCancelSynchronousIoEvent(reason, attempted, succeeded, code, symbol);
#else
    AddCancelSynchronousIoEvent(
        reason, false, false, 0, "CANCEL_SYNCHRONOUS_IO_NOT_AVAILABLE");
#endif
  }

  void AddCancelSynchronousIoEvent(std::string_view reason,
                                   bool attempted,
                                   bool succeeded,
                                   int code,
                                   const char* symbol) {
    DiagnosticEvent event;
    event.type = DiagnosticEventType::kRuntimeStats;
    event.sequence = NextSequence();
    event.backend = BackendApi::kKernelStreaming;
    event.device_id = config_.device.stable_id;
    event.message = "Kernel Streaming render-thread cancellation requested";
    event.backend_fields["api"] = "CancelSynchronousIo";
    event.backend_fields["cancel_synchronous_io_attempted"] =
        attempted ? "true" : "false";
    event.backend_fields["cancel_synchronous_io_succeeded"] =
        succeeded ? "true" : "false";
    event.backend_fields["cancel_synchronous_io_failure_is_fatal"] = "false";
    event.backend_fields["join_timeout_is_authoritative"] = "true";
    event.backend_fields["release_reason"] = std::string(reason);
    event.backend_fields["code"] = std::to_string(code);
    event.backend_fields["code_signed"] = std::to_string(code);
    event.backend_fields["code_hex"] = CodeHexForDomain(code, "win32");
    event.backend_fields["code_domain"] = "win32";
    event.backend_fields["symbol"] = symbol;
    AddCommonKernelStreamingEvidence(event, "release");
    AppendEvent(std::move(event));
  }

  void AddRenderThreadCancelHandleEvent(bool available,
                                        int code,
                                        const char* symbol) {
    DiagnosticEvent event;
    event.type = DiagnosticEventType::kRuntimeStats;
    event.sequence = NextSequence();
    event.backend = BackendApi::kKernelStreaming;
    event.device_id = config_.device.stable_id;
    event.message = available
        ? "Kernel Streaming render-thread cancellation handle registered"
        : "Kernel Streaming render-thread cancellation handle unavailable";
    event.backend_fields["api"] = "DuplicateHandle";
    event.backend_fields["render_thread_cancel_handle_available"] =
        available ? "true" : "false";
    event.backend_fields["code"] = std::to_string(code);
    event.backend_fields["code_signed"] = std::to_string(code);
    event.backend_fields["code_hex"] = CodeHexForDomain(code, "win32");
    event.backend_fields["code_domain"] = "win32";
    event.backend_fields["symbol"] = symbol;
    AddCommonKernelStreamingEvidence(event, "release");
    AppendEvent(std::move(event));
  }

  void AddRenderThreadJoinTimeoutEvent(std::string_view reason) {
    DiagnosticEvent event;
    event.type = DiagnosticEventType::kError;
    event.sequence = NextSequence();
    event.backend = BackendApi::kKernelStreaming;
    event.device_id = config_.device.stable_id;
    event.message = kKsRenderThreadJoinTimeoutMessage;
    event.backend_fields["api"] = "DeviceIoControl(IOCTL_KS_WRITE_STREAM)";
    event.backend_fields["code"] =
        std::to_string(kKsRenderThreadJoinTimeout);
    event.backend_fields["code_signed"] =
        std::to_string(kKsRenderThreadJoinTimeout);
    event.backend_fields["code_hex"] =
        CodeHexForDomain(kKsRenderThreadJoinTimeout, "internal");
    event.backend_fields["code_domain"] = "internal";
    event.backend_fields["symbol"] = kKsRenderThreadJoinTimeoutSymbol;
    event.backend_fields["release_reason"] = std::string(reason);
    event.backend_fields["render_thread_join_timeout_ms"] =
        std::to_string(kKsRenderThreadJoinTimeoutMs);
    event.backend_fields["handles_open_after_release"] =
        HandlesOpen() ? "true" : "false";
    AddCommonKernelStreamingEvidence(event, "release");
    AppendEvent(std::move(event));
  }

  void FinalizeRenderThreadForDestruction() {
    if (!render_thread_.joinable()) {
      CloseRenderThreadCancelHandle();
      return;
    }

    // Normal UI release may time out and keep this backend alive/faulted so the
    // user can retry after the driver returns from synchronous KS I/O. Object
    // destruction has a stricter rule: the render thread captures `this`, so the
    // destructor must wait and join instead of detaching or letting std::thread
    // call std::terminate.
    render_thread_stop_ = true;
    AddFinalDestructorCleanupEvent(
        "Kernel Streaming final destructor cleanup waiting for render thread; "
        "normal release timeout keeps backend active for retry");
    RequestRenderThreadCancellation("destructor");
    while (!render_thread_exited_.load(std::memory_order_acquire)) {
      std::this_thread::sleep_for(std::chrono::milliseconds(20));
    }
    render_thread_.join();
    CloseRenderThreadCancelHandle();
    AddFinalDestructorCleanupEvent(
        "Kernel Streaming final destructor cleanup joined render thread before "
        "member destruction");
  }

  void AddFinalDestructorCleanupEvent(std::string message) {
    DiagnosticEvent event;
    event.type = DiagnosticEventType::kRuntimeStats;
    event.sequence = NextSequence();
    event.backend = BackendApi::kKernelStreaming;
    event.device_id = config_.device.stable_id;
    event.message = std::move(message);
    event.backend_fields["api"] = "KernelStreamingPcmBackend::~Impl";
    event.backend_fields["destructor_blocks_until_render_thread_joined"] =
        "true";
    event.backend_fields["normal_release_timeout_retry_policy"] =
        "backend_retained_faulted_for_retry";
    event.backend_fields["detach_used"] = "false";
    event.backend_fields["handles_open_after_release"] =
        HandlesOpen() ? "true" : "false";
    AddCommonKernelStreamingEvidence(event, "release");
    AppendEvent(std::move(event));
  }

  void ReleaseHandles() {
#if defined(APTT_HAS_WINDOWS_KS_PCM_HEADERS)
    if (pin_handle_.valid() && wavert_notification_registered_ &&
        wavert_notification_event_.valid()) {
      auto unregister_result =
          UnregisterKernelStreamingWaveRtNotificationEvent(
              pin_handle_.get(),
              wavert_notification_event_.get());
      AddWaveRtNotificationEvent("unregister", unregister_result);
    }
    wavert_notification_registered_ = false;
    wavert_notification_event_.reset();
    wavert_buffer_address_ = nullptr;
    wavert_buffer_bytes_ = 0;
    wavert_period_bytes_ = 0;
    wavert_period_frames_ = 0;
    wavert_call_memory_barrier_ = false;
    pin_handle_.reset();
    filter_handle_.reset();
#endif
  }

  bool HandlesOpen() const {
#if defined(APTT_HAS_WINDOWS_KS_PCM_HEADERS)
    return pin_handle_.valid() || filter_handle_.valid();
#else
    return false;
#endif
  }

  std::uint32_t RequestedWaveRtBufferBytes() const {
    const std::uint64_t tenth_second_bytes =
        (static_cast<std::uint64_t>(config_.format.sample_rate_hz) *
         bytes_per_frame_) /
        10;
    const std::uint64_t minimum_bytes =
        static_cast<std::uint64_t>(bytes_per_frame_) * 128;
    const std::uint64_t requested =
        std::max(minimum_bytes, tenth_second_bytes);
    return static_cast<std::uint32_t>(
        std::min<std::uint64_t>(requested,
                                std::numeric_limits<std::uint32_t>::max()));
  }

  PcmSineConfig MakeSignalConfig() const {
    PcmSineConfig signal;
    signal.sample_rate_hz = config_.format.sample_rate_hz;
    signal.channel_count = config_.format.channels.channel_count;
    signal.frequency_hz = config_.frequency_hz;
    signal.amplitude_dbfs = config_.amplitude_dbfs;
    signal.invert_right = config_.invert_right_phase;
    signal.right_channel_phase_offset_degrees =
        config_.right_channel_phase_offset_degrees;
    if (config_.left_channel_enabled && config_.right_channel_enabled) {
      signal.channel_assignment = ChannelAssignment::kAllChannels;
    } else if (config_.left_channel_enabled) {
      signal.channel_assignment = ChannelAssignment::kLeftOnly;
    } else if (config_.right_channel_enabled) {
      signal.channel_assignment = ChannelAssignment::kRightOnly;
    }
    return signal;
  }

  OperationResult WriteWaveRtBytes(std::uint32_t offset_bytes,
                                   std::uint32_t frames) {
    if (wavert_buffer_address_ == nullptr || wavert_buffer_bytes_ == 0 ||
        bytes_per_frame_ == 0) {
      return OperationResult::Failure(
          kKsNotInitialized,
          "Kernel Streaming WaveRT buffer is not initialized");
    }
    const auto bytes = NextPacketBytes(frames);
    if (bytes.empty()) {
      return OperationResult::Failure(
          kKsInvalidArgument,
          "Kernel Streaming WaveRT packet generation returned no bytes");
    }
    const std::uint32_t writable_bytes =
        std::min<std::uint32_t>(
            static_cast<std::uint32_t>(bytes.size()),
            wavert_buffer_bytes_ - offset_bytes);
    std::memcpy(static_cast<std::uint8_t*>(wavert_buffer_address_) +
                    offset_bytes,
                bytes.data(),
                writable_bytes);
    if (wavert_call_memory_barrier_) {
      MemoryBarrier();
    }
    return OperationResult::Success();
  }

  OperationResult PrimeWaveRtCyclicBuffer() {
    if (playback_path_ != KernelStreamingPlaybackPath::kWaveRtCyclic) {
      return OperationResult::Success();
    }
    if (wavert_buffer_bytes_ == 0 || bytes_per_frame_ == 0) {
      return OperationResult::Failure(
          kKsNotInitialized,
          "Kernel Streaming WaveRT buffer has no writable range");
    }
    const std::uint32_t frames = wavert_buffer_bytes_ / bytes_per_frame_;
    return WriteWaveRtBytes(0, frames);
  }

  std::vector<std::uint8_t> NextPacketBytes(std::uint32_t frames) {
    const bool write_silence = force_silence_ ||
                               signal_frames_written_ >= target_frames_;
    if (IsDopMode(config_.format)) {
      const auto dop_config = DopConfigFromFormat(config_.format);
      if (write_silence) {
        const auto silence = dop_generator_.GenerateSilence(dop_config, frames);
        if (!silence.ok) {
          AddErrorEvent(kKsInvalidArgument,
                        "GenerateDopSilence",
                        silence.error);
          return {};
        }
        return silence.bytes;
      }

      const auto remaining = target_frames_ - signal_frames_written_;
      const auto signal_frames = static_cast<std::uint32_t>(
          std::min<std::uint64_t>(frames, remaining));
      DopSineConfig signal;
      signal.dop = dop_config;
      signal.frequency_hz = config_.frequency_hz;
      signal.amplitude_dbfs = config_.amplitude_dbfs;
      auto packet = dop_generator_.GenerateSine(signal, signal_frames);
      if (!packet.ok) {
        AddErrorEvent(kKsInvalidArgument,
                      "GenerateDopSine",
                      packet.error);
        return {};
      }
      if (signal_frames < frames) {
        const auto silence =
            dop_generator_.GenerateSilence(dop_config, frames - signal_frames);
        if (!silence.ok) {
          AddErrorEvent(kKsInvalidArgument,
                        "GenerateDopSilence",
                        silence.error);
          return {};
        }
        packet.bytes.insert(
            packet.bytes.end(),
            silence.bytes.begin(),
            silence.bytes.end());
      }
      signal_frames_written_ += signal_frames;
      return packet.bytes;
    }

    std::vector<float> interleaved;
    if (write_silence) {
      interleaved = GenerateInterleavedSilenceFloat32(
          frames,
          config_.format.channels.channel_count);
    } else {
      const auto remaining = target_frames_ - signal_frames_written_;
      const auto signal_frames = static_cast<std::uint32_t>(
          std::min<std::uint64_t>(frames, remaining));
      interleaved = generator_.GenerateInterleavedFloat32(
          MakeSignalConfig(),
          signal_frames);
      if (signal_frames < frames) {
        const auto silence = GenerateInterleavedSilenceFloat32(
            frames - signal_frames,
            config_.format.channels.channel_count);
        interleaved.insert(interleaved.end(), silence.begin(), silence.end());
      }
      signal_frames_written_ += signal_frames;
    }
    return ConvertFloat32InterleavedToKernelStreamingPcmBytes(
        interleaved,
        config_.format.channels.channel_count,
        config_.format);
  }

  void UpdateStatsAfterPacket(const OperationResult& write,
                              std::uint32_t frames,
                              std::chrono::steady_clock::time_point packet_end) {
    std::lock_guard lock(stats_mutex_);
    ++stats_.callback_count;
    stats_.frames_submitted += frames;
    if (write.ok) {
      stats_.frames_accepted += frames;
    } else {
      ++stats_.underrun_count;
    }
    if (!force_silence_) {
      stats_.frames_generated =
          std::min<std::uint64_t>(signal_frames_written_, target_frames_);
    }
    const double interval_ms =
        std::chrono::duration<double, std::milli>(
            packet_end - last_packet_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_);
  }

  bool HandleSignalDurationAfterPacket() {
    if (!config_.continuous &&
        signal_frames_written_ >= target_frames_ &&
        !policy_.keep_warm_after_signal) {
      render_thread_stop_ = true;
      return true;
    }
    if (!config_.continuous &&
        signal_frames_written_ >= target_frames_ &&
        policy_.keep_warm_after_signal &&
        GetState() == DeviceLifecycleState::kRunningSignal) {
      force_silence_ = true;
      const std::string silence_message = IsDopMode(config_.format)
          ? "Kernel Streaming signal duration complete; valid DoP silence continues"
          : "Kernel Streaming signal duration complete; valid PCM silence continues";
      TransitionTo(DeviceLifecycleState::kRunningSilence,
                   silence_message);
    }
    return false;
  }

  void RenderStandardWriteStreamLoop() {
#if defined(APTT_HAS_WINDOWS_KS_PCM_HEADERS)
    while (!render_thread_stop_) {
      ApplyHighLoadRenderDelay(config_, GetRealtimeStats().callback_count);
      const auto packet_start = std::chrono::steady_clock::now();
      const auto bytes = NextPacketBytes(packet_frames_);
      auto write = bytes.empty()
          ? OperationResult::Failure(
                kKsInvalidArgument,
                "Kernel Streaming packet generation returned no bytes")
          : WriteKernelStreamingPacket(pin_handle_.get(),
                                       bytes,
                                       packet_frames_,
                                       config_.format.sample_rate_hz);
      const auto packet_end = std::chrono::steady_clock::now();
      const double write_duration_ms =
          std::chrono::duration<double, std::milli>(
              packet_end - packet_start)
              .count();
      UpdateStatsAfterPacket(write, packet_frames_, packet_end);
      last_packet_time_ = packet_end;
      AddRuntimeEvent(write_duration_ms, packet_frames_);
      if (!write.ok) {
        AddErrorEvent(write.error.code,
                      "DeviceIoControl(IOCTL_KS_WRITE_STREAM)",
                      write.error.message,
                      "win32",
                      "stream_write");
        TransitionTo(DeviceLifecycleState::kFaulted,
                     "Kernel Streaming write packet failed");
        render_thread_stop_ = true;
        break;
      }
      HandleSignalDurationAfterPacket();
    }
#endif
  }

  void RenderWaveRtCyclicBufferLoop() {
#if defined(APTT_HAS_WINDOWS_KS_PCM_HEADERS)
    std::uint32_t offset_bytes = 0;
    while (!render_thread_stop_) {
      if (wavert_period_frames_ == 0 || wavert_period_bytes_ == 0) {
        AddErrorEvent(kKsNotInitialized,
                      "WaveRT cyclic buffer",
                      "Kernel Streaming WaveRT period is not initialized",
                      "internal",
                      "stream_write");
        TransitionTo(DeviceLifecycleState::kFaulted,
                     "Kernel Streaming WaveRT period is not initialized");
        render_thread_stop_ = true;
        break;
      }

      if (wavert_notification_registered_ &&
          wavert_notification_event_.valid()) {
        const DWORD wait_ms = std::max<DWORD>(
            100,
            static_cast<DWORD>(
                (static_cast<std::uint64_t>(wavert_period_frames_) * 2000ULL) /
                std::max<std::uint32_t>(1, config_.format.sample_rate_hz)));
        const DWORD wait_result =
            WaitForSingleObject(wavert_notification_event_.get(), wait_ms);
        if (wait_result == WAIT_FAILED) {
          const int code = static_cast<int>(::GetLastError());
          AddErrorEvent(code,
                        "WaitForSingleObject(WaveRT notification)",
                        "Kernel Streaming WaveRT notification wait failed",
                        "win32",
                        "stream_write",
                        Win32Symbol(code));
          TransitionTo(DeviceLifecycleState::kFaulted,
                       "Kernel Streaming WaveRT notification wait failed");
          render_thread_stop_ = true;
          break;
        }
      } else {
        const DWORD sleep_ms = std::max<DWORD>(
            5,
            static_cast<DWORD>(
                (static_cast<std::uint64_t>(wavert_period_frames_) * 1000ULL) /
                std::max<std::uint32_t>(1, config_.format.sample_rate_hz)));
        Sleep(sleep_ms);
      }

      if (render_thread_stop_) {
        break;
      }

      ApplyHighLoadRenderDelay(config_, GetRealtimeStats().callback_count);
      const auto packet_start = std::chrono::steady_clock::now();
      auto write = WriteWaveRtBytes(offset_bytes, wavert_period_frames_);
      const auto packet_end = std::chrono::steady_clock::now();
      const double write_duration_ms =
          std::chrono::duration<double, std::milli>(
              packet_end - packet_start)
              .count();
      UpdateStatsAfterPacket(write, wavert_period_frames_, packet_end);
      last_packet_time_ = packet_end;
      AddRuntimeEvent(write_duration_ms, wavert_period_frames_);
      if (!write.ok) {
        AddErrorEvent(write.error.code,
                      "WaveRT cyclic buffer memory write",
                      write.error.message,
                      "internal",
                      "stream_write");
        TransitionTo(DeviceLifecycleState::kFaulted,
                     "Kernel Streaming WaveRT cyclic buffer write failed");
        render_thread_stop_ = true;
        break;
      }

      HandleSignalDurationAfterPacket();
      offset_bytes += wavert_period_bytes_;
      if (offset_bytes + wavert_period_bytes_ > wavert_buffer_bytes_) {
        offset_bytes = 0;
      }
    }
#endif
  }

  void RenderLoop() {
    struct ExitFlag {
      std::atomic_bool& value;
      ~ExitFlag() { value.store(true, std::memory_order_release); }
    } exit_flag{render_thread_exited_};

    RegisterRenderThreadCancelHandle();

    ScopedAudioThreadMmcssRegistration mmcss({
        .enabled = config_.audio_thread_mmcss_enabled,
        .task_name = config_.audio_thread_mmcss_task_name,
        .priority = config_.audio_thread_mmcss_priority,
    });
    AddThreadSchedulingEvent(mmcss.snapshot(),
                             "Kernel Streaming render thread MMCSS registration");

    if (playback_path_ == KernelStreamingPlaybackPath::kWaveRtCyclic) {
      RenderWaveRtCyclicBufferLoop();
    } else {
      RenderStandardWriteStreamLoop();
    }

    AddThreadSchedulingEvent(mmcss.Revert(),
                             "Kernel Streaming render thread MMCSS revert");
  }

  PlaybackConfig config_;
  KernelStreamingPcmPolicy policy_;
  mutable std::mutex state_mutex_;
  mutable std::mutex stats_mutex_;
  mutable std::mutex error_mutex_;
  mutable std::mutex events_mutex_;
  DeviceLifecycleState state_ = DeviceLifecycleState::kDiscovered;
  RealtimeStats stats_;
  BackendError last_error_;
  std::vector<DiagnosticEvent> events_;
  DiagnosticSequenceCounter sequence_;
  std::uint64_t target_frames_ = 0;
  std::uint64_t signal_frames_written_ = 0;
  std::uint32_t packet_frames_ = 0;
  std::uint32_t bytes_per_frame_ = 0;
  std::atomic_bool render_thread_stop_{false};
  std::atomic_bool render_thread_exited_{true};
  std::atomic_bool force_silence_{false};
  std::thread render_thread_;
  PcmSineGenerator generator_;
  DopSineGenerator dop_generator_;
  std::chrono::steady_clock::time_point last_packet_time_{};
  KernelStreamingPlaybackPath playback_path_ =
      KernelStreamingPlaybackPath::kStandardPacket;
  std::string ks_filter_path_;
  std::string ks_interface_label_;
  std::string ks_medium_label_;
  std::uint32_t ks_pin_id_ = 0;
#if defined(_WIN32)
  mutable std::mutex render_thread_cancel_handle_mutex_;
  HANDLE render_thread_cancel_handle_ = nullptr;
#endif
#if defined(APTT_HAS_WINDOWS_KS_PCM_HEADERS)
  ScopedHandle filter_handle_;
  ScopedHandle pin_handle_;
  ScopedHandle wavert_notification_event_;
  void* wavert_buffer_address_ = nullptr;
  std::uint32_t wavert_buffer_bytes_ = 0;
  std::uint32_t wavert_period_bytes_ = 0;
  std::uint32_t wavert_period_frames_ = 0;
  bool wavert_call_memory_barrier_ = false;
  bool wavert_notification_registered_ = false;
#endif
};

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

KernelStreamingPcmBackend::~KernelStreamingPcmBackend() = default;

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

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

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

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

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

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

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

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

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

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

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

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

}  // namespace aptt
