#include "backends/kernel_streaming_discovery.h"

#include <algorithm>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <iterator>
#include <limits>
#include <map>
#include <optional>
#include <sstream>
#include <string_view>
#include <thread>
#include <utility>
#include <vector>

#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(<setupapi.h>) && __has_include(<ks.h>) && \
    __has_include(<ksmedia.h>)
#define APTT_HAS_WINDOWS_KS_HEADERS 1
#include <initguid.h>
#include <objbase.h>
#include <setupapi.h>
#include <winioctl.h>
#include <ks.h>
#include <ksmedia.h>
#include <mmreg.h>
#endif
#endif
#endif

namespace aptt {
namespace {

constexpr std::int32_t kHresultInvalidArg =
    static_cast<std::int32_t>(0x80070057u);
constexpr std::int32_t kHresultNotImplemented =
    static_cast<std::int32_t>(0x80004001u);
constexpr std::uint32_t kMaxKernelStreamingFilters = 64;
constexpr std::uint32_t kMaxKernelStreamingPinsPerFilter = 64;
constexpr std::uint32_t kMaxKernelStreamingDataRangeBytes = 64 * 1024;
constexpr std::uint32_t kMaxKernelStreamingDataRanges = 256;

bool SameFormatDescriptor(const FormatDescriptor& left,
                          const FormatDescriptor& right) {
  return left.signal_mode == right.signal_mode &&
         left.sample_rate_hz == right.sample_rate_hz &&
         left.sample_type == right.sample_type &&
         left.valid_bits_per_sample == right.valid_bits_per_sample &&
         left.container_bits_per_sample == right.container_bits_per_sample &&
         left.channels.channel_count == right.channels.channel_count &&
         left.channels.channel_mask == right.channels.channel_mask &&
         left.dsd_rate_multiplier == right.dsd_rate_multiplier;
}

void PushUniqueFormat(std::vector<FormatDescriptor>& formats,
                      const FormatDescriptor& candidate) {
  const auto found = std::find_if(
      formats.begin(),
      formats.end(),
      [&](const FormatDescriptor& existing) {
        return SameFormatDescriptor(existing, candidate);
      });
  if (found == formats.end()) {
    formats.push_back(candidate);
  }
}

DeviceCapabilitySnapshot MakeKernelStreamingFailure(std::string stable_id,
                                                    ApiErrorInfo error) {
  const auto error_evidence = error;
  DeviceInfo device;
  device.backend = BackendApi::kKernelStreaming;
  device.display_name = "Selected Kernel Streaming pin";
  device.stable_id = std::move(stable_id);
  device.driver_name = "KS/AVStream";

  auto snapshot = MakeDiscoveredDeviceSnapshot(
      std::move(device),
      DeviceAvailability::kUnavailable);
  snapshot.discovery_error = std::move(error);
  snapshot.backend_fields["api"] = "Kernel Streaming";
  snapshot.backend_fields["event_category"] = "probe";
  snapshot.backend_fields["code_signed"] =
      std::to_string(error_evidence.raw_code);
  snapshot.backend_fields["code_hex"] = error_evidence.raw_code_hex;
  snapshot.backend_fields["code_domain"] = "unknown";
  snapshot.backend_fields["symbol"] = error_evidence.symbol;
  snapshot.backend_fields["opens_filter"] = "false";
  snapshot.backend_fields["creates_pin"] = "false";
  snapshot.backend_fields["starts_stream"] = "false";
  return snapshot;
}

CapabilityProbeRecord MakeKernelStreamingFormatProbeRecord(
    const FormatDescriptor& requested,
    CapabilitySupport support,
    std::string detail) {
  CapabilityProbeRecord record;
  record.kind = CapabilityProbeKind::kFormatSupport;
  record.support = support;
  record.requested_format = requested;
  if (support == CapabilitySupport::kSupported) {
    record.accepted_format = requested;
  }
  record.detail = std::move(detail);
  record.backend_fields["api"] = "Kernel Streaming pin format probe";
  record.backend_fields["event_category"] = "probe";
  record.backend_fields["starts_stream"] = "false";
  return record;
}

#if defined(APTT_HAS_WINDOWS_KS_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);
}

void AddErrorEvidence(std::map<std::string, std::string>& fields,
                      const ApiErrorInfo& error,
                      std::string_view code_domain) {
  fields["code_signed"] = std::to_string(error.raw_code);
  fields["code_hex"] = HexCode32ForDomain(error.raw_code, code_domain);
  fields["code_domain"] = std::string(code_domain);
  fields["symbol"] = error.symbol;
}

const char* AccessMaskLabel(DWORD access) {
  if (access == GENERIC_READ) {
    return "GENERIC_READ";
  }
  if (access == (GENERIC_READ | GENERIC_WRITE)) {
    return "GENERIC_READ|GENERIC_WRITE";
  }
  if (access == GENERIC_WRITE) {
    return "GENERIC_WRITE";
  }
  return "custom";
}

std::string WideToUtf8(const wchar_t* value) {
  if (value == nullptr || value[0] == L'\0') {
    return {};
  }
  const int required =
      WideCharToMultiByte(CP_UTF8, 0, value, -1, nullptr, 0, nullptr, nullptr);
  if (required <= 1) {
    return {};
  }
  std::string converted(static_cast<std::size_t>(required - 1), '\0');
  WideCharToMultiByte(
      CP_UTF8, 0, value, -1, converted.data(), required, nullptr, nullptr);
  return converted;
}

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

std::string GuidToString(const GUID& guid) {
  wchar_t buffer[64]{};
  const int written = StringFromGUID2(guid, buffer, 64);
  if (written <= 1) {
    return {};
  }
  return WideToUtf8(buffer);
}

std::string PinDataflowName(KSPIN_DATAFLOW dataflow) {
  switch (dataflow) {
    case KSPIN_DATAFLOW_IN:
      return "render";
    case KSPIN_DATAFLOW_OUT:
      return "capture";
  }
  return "unknown";
}

std::string PinCommunicationName(KSPIN_COMMUNICATION communication) {
  switch (communication) {
    case KSPIN_COMMUNICATION_NONE:
      return "none";
    case KSPIN_COMMUNICATION_SINK:
      return "sink";
    case KSPIN_COMMUNICATION_SOURCE:
      return "source";
    case KSPIN_COMMUNICATION_BOTH:
      return "both";
    case KSPIN_COMMUNICATION_BRIDGE:
      return "bridge";
  }
  return "unknown";
}

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

std::string KernelStreamingInterfaceLabel(const KSPIN_INTERFACE& value) {
  if (IsEqualGUID(value.Set, KSINTERFACESETID_Standard)) {
    if (value.Id == KSINTERFACE_STANDARD_STREAMING) {
      return "KSINTERFACE_STANDARD_STREAMING";
    }
    if (value.Id == KSINTERFACE_STANDARD_LOOPED_STREAMING) {
      return "KSINTERFACE_STANDARD_LOOPED_STREAMING";
    }
    return "KSINTERFACESETID_Standard/" + std::to_string(value.Id);
  }
  return GuidToString(value.Set) + "/" + 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 GuidToString(value.Set) + "/" + std::to_string(value.Id);
}

template <typename T>
std::vector<T> QueryPinPropertyArray(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) {
    return {};
  }
  if (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);
}

bool PinSupportsStandardStreamingWrites(HANDLE filter, ULONG pin_id) {
  const auto interfaces =
      QueryPinPropertyArray<KSPIN_INTERFACE>(
          filter,
          pin_id,
          KSPROPERTY_PIN_INTERFACES);
  return std::any_of(interfaces.begin(),
                     interfaces.end(),
                     IsKernelStreamingStandardStreamingInterface);
}

bool PinSupportsLoopedStreaming(HANDLE filter, ULONG pin_id) {
  const auto interfaces =
      QueryPinPropertyArray<KSPIN_INTERFACE>(
          filter,
          pin_id,
          KSPROPERTY_PIN_INTERFACES);
  return std::any_of(interfaces.begin(),
                     interfaces.end(),
                     IsKernelStreamingLoopedStreamingInterface);
}

bool QueryRtAudioPropertyBasicSupport(HANDLE pin, ULONG property_id) {
  KSPROPERTY property{};
  property.Set = KSPROPSETID_RtAudio;
  property.Id = property_id;
  property.Flags = KSPROPERTY_TYPE_BASICSUPPORT;
  KSPROPERTY_DESCRIPTION description{};
  DWORD returned = 0;
  return DeviceIoControl(pin,
                         IOCTL_KS_PROPERTY,
                         &property,
                         sizeof(property),
                         &description,
                         sizeof(description),
                         &returned,
                         nullptr) != FALSE;
}

std::uint32_t RequestedWaveRtProbeBufferBytes(
    const FormatDescriptor& format) {
  const std::uint32_t bytes_per_frame =
      (format.channels.channel_count * format.container_bits_per_sample) / 8;
  if (bytes_per_frame == 0 || format.sample_rate_hz == 0) {
    return 4096;
  }
  const std::uint64_t tenth_second_bytes =
      (static_cast<std::uint64_t>(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()));
}

bool ProbeWaveRtNotificationBuffer(HANDLE pin,
                                   const FormatDescriptor& format) {
  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 = RequestedWaveRtProbeBufferBytes(format);
  property.NotificationCount = 2;

  KSRTAUDIO_BUFFER buffer{};
  DWORD returned = 0;
  const BOOL ok = DeviceIoControl(pin,
                                  IOCTL_KS_PROPERTY,
                                  &property,
                                  sizeof(property),
                                  &buffer,
                                  sizeof(buffer),
                                  &returned,
                                  nullptr);
  return ok != FALSE && buffer.BufferAddress != nullptr &&
         buffer.ActualBufferSize > 0;
}

bool DetectWaveRtRtAudioBasicSupport(HANDLE pin) {
  return QueryRtAudioPropertyBasicSupport(pin, KSPROPERTY_RTAUDIO_BUFFER) ||
         QueryRtAudioPropertyBasicSupport(
             pin,
             KSPROPERTY_RTAUDIO_BUFFER_WITH_NOTIFICATION) ||
         QueryRtAudioPropertyBasicSupport(pin, KSPROPERTY_RTAUDIO_PACKETCOUNT) ||
         QueryRtAudioPropertyBasicSupport(
             pin,
             KSPROPERTY_RTAUDIO_PRESENTATION_POSITION) ||
         QueryRtAudioPropertyBasicSupport(pin, KSPROPERTY_RTAUDIO_SETWRITEPACKET);
}

KernelStreamingStreamingModelMetadata ClassifyKernelStreamingModel(
    const std::vector<KSPIN_INTERFACE>& interfaces,
    std::string supports_wavert_rtaudio_properties,
    std::string accepts_wavert_notification_buffer = "unknown") {
  const bool supports_standard_streaming =
      std::any_of(interfaces.begin(),
                  interfaces.end(),
                  IsKernelStreamingStandardStreamingInterface);
  const bool supports_looped_streaming =
      std::any_of(interfaces.begin(),
                  interfaces.end(),
                  IsKernelStreamingLoopedStreamingInterface);
  std::string pin_interface_set = "unknown";
  std::string pin_interface_id = "unknown";
  if (accepts_wavert_notification_buffer == "true" &&
      supports_looped_streaming) {
    const auto looped = std::find_if(
        interfaces.begin(),
        interfaces.end(),
        IsKernelStreamingLoopedStreamingInterface);
    pin_interface_set = GuidToString(looped->Set);
    pin_interface_id = std::to_string(looped->Id);
  } else if (supports_standard_streaming) {
    const auto streaming = std::find_if(
        interfaces.begin(),
        interfaces.end(),
        IsKernelStreamingStandardStreamingInterface);
    pin_interface_set = GuidToString(streaming->Set);
    pin_interface_id = std::to_string(streaming->Id);
  } else if (supports_looped_streaming) {
    const auto looped = std::find_if(
        interfaces.begin(),
        interfaces.end(),
        IsKernelStreamingLoopedStreamingInterface);
    pin_interface_set = GuidToString(looped->Set);
    pin_interface_id = std::to_string(looped->Id);
  } else if (!interfaces.empty()) {
    pin_interface_set = GuidToString(interfaces.front().Set);
    pin_interface_id = std::to_string(interfaces.front().Id);
  }

  return ClassifyKernelStreamingStreamingModel(
      supports_standard_streaming,
      supports_looped_streaming,
      std::move(supports_wavert_rtaudio_properties),
      std::move(pin_interface_set),
      std::move(pin_interface_id),
      std::move(accepts_wavert_notification_buffer));
}

void AddKernelStreamingModelFields(
    std::map<std::string, std::string>& fields,
    const KernelStreamingStreamingModelMetadata& model) {
  fields["ks_streaming_model"] = model.streaming_model;
  fields["ks_pin_interface_set"] = model.pin_interface_set;
  fields["ks_pin_interface_id"] = model.pin_interface_id;
  fields["supports_standard_streaming"] =
      model.supports_standard_streaming ? "true" : "false";
  fields["supports_looped_streaming"] =
      model.supports_looped_streaming ? "true" : "false";
  fields["supports_wavert_rtaudio_properties"] =
      model.supports_wavert_rtaudio_properties;
  fields["accepts_wavert_notification_buffer"] =
      model.accepts_wavert_notification_buffer;
  fields["ks_playback_implementation"] = model.playback_implementation;
  fields["ks_playback_path"] = model.playback_implementation == "implemented"
                                   ? model.streaming_model
                                   : "unimplemented";
  fields["ks_current_packet_playback_model"] =
      model.streaming_model == "standard_packet" ? "standard_packet"
                                                 : "not_selected";

  // Transitional aliases kept for existing diagnostics and tests.
  fields["ks_stream_write_supported"] =
      model.supports_standard_streaming ? "true" : "false";
  fields["ks_standard_streaming_supported"] =
      model.supports_standard_streaming ? "true" : "false";
  fields["ks_looped_streaming_supported"] =
      model.supports_looped_streaming ? "true" : "false";
  fields["ks_streaming_interface_supported"] =
      (model.supports_standard_streaming || model.supports_looped_streaming)
          ? "true"
          : "false";
  fields["ks_transfer_mode"] = model.streaming_model;
  fields["ks_looped_streaming_only"] =
      model.supports_looped_streaming && !model.supports_standard_streaming
          ? "true"
          : "false";
}

std::optional<KSPIN_INTERFACE> SelectKernelStreamingPlaybackInterface(
    const std::vector<KSPIN_INTERFACE>& interfaces) {
  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;
  }
  return std::nullopt;
}

std::optional<KSPIN_INTERFACE> SelectKernelStreamingWaveRtProbeInterface(
    const std::vector<KSPIN_INTERFACE>& interfaces) {
  const auto looped = std::find_if(
      interfaces.begin(),
      interfaces.end(),
      IsKernelStreamingLoopedStreamingInterface);
  if (looped != interfaces.end()) {
    return *looped;
  }
  return std::nullopt;
}

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 SpecifierName(const GUID& guid) {
  if (IsEqualGUID(guid, KSDATAFORMAT_SPECIFIER_WAVEFORMATEX)) {
    return "KSDATAFORMAT_SPECIFIER_WAVEFORMATEX";
  }
  if (IsEqualGUID(guid, KSDATAFORMAT_SPECIFIER_DSOUND)) {
    return "KSDATAFORMAT_SPECIFIER_DSOUND";
  }
  if (IsEqualGUID(guid, KSDATAFORMAT_SPECIFIER_NONE)) {
    return "KSDATAFORMAT_SPECIFIER_NONE";
  }
  if (IsEqualGUID(guid, GUID_NULL)) {
    return "GUID_NULL";
  }
  return GuidToString(guid);
}

std::string SubFormatName(const GUID& guid) {
  if (IsEqualGUID(guid, KSDATAFORMAT_SUBTYPE_PCM)) {
    return "KSDATAFORMAT_SUBTYPE_PCM";
  }
  if (IsEqualGUID(guid, KSDATAFORMAT_SUBTYPE_IEEE_FLOAT)) {
    return "KSDATAFORMAT_SUBTYPE_IEEE_FLOAT";
  }
  if (IsEqualGUID(guid, KSDATAFORMAT_SUBTYPE_WILDCARD)) {
    return "KSDATAFORMAT_SUBTYPE_WILDCARD";
  }
  return GuidToString(guid);
}

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;
  }
  void reset(HANDLE next = nullptr) {
    if (valid()) {
      CloseHandle(handle_);
    }
    handle_ = next;
  }

 private:
  HANDLE handle_ = nullptr;
};

class ScopedDeviceInfoSet {
 public:
  explicit ScopedDeviceInfoSet(HDEVINFO handle) : handle_(handle) {}
  ScopedDeviceInfoSet(const ScopedDeviceInfoSet&) = delete;
  ScopedDeviceInfoSet& operator=(const ScopedDeviceInfoSet&) = delete;
  ~ScopedDeviceInfoSet() {
    if (handle_ != INVALID_HANDLE_VALUE) {
      SetupDiDestroyDeviceInfoList(handle_);
    }
  }

  HDEVINFO get() const { return handle_; }
  bool valid() const { return handle_ != INVALID_HANDLE_VALUE; }

 private:
  HDEVINFO handle_ = INVALID_HANDLE_VALUE;
};

bool QueryKsProperty(HANDLE handle,
                     void* input,
                     DWORD input_size,
                     void* output,
                     DWORD output_size,
                     DWORD* bytes_returned) {
  DWORD local_returned = 0;
  const BOOL ok = DeviceIoControl(handle,
                                  IOCTL_KS_PROPERTY,
                                  input,
                                  input_size,
                                  output,
                                  output_size,
                                  bytes_returned != nullptr ? bytes_returned
                                                            : &local_returned,
                                  nullptr);
  return ok != FALSE;
}

std::optional<ULONG> QueryPinCount(HANDLE filter) {
  KSPROPERTY property{};
  property.Set = KSPROPSETID_Pin;
  property.Id = KSPROPERTY_PIN_CTYPES;
  property.Flags = KSPROPERTY_TYPE_GET;
  ULONG pin_count = 0;
  DWORD returned = 0;
  if (!QueryKsProperty(filter,
                       &property,
                       sizeof(property),
                       &pin_count,
                       sizeof(pin_count),
                       &returned)) {
    return std::nullopt;
  }
  return pin_count;
}

template <typename T>
std::optional<T> QueryPinProperty(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;
  if (!QueryKsProperty(filter,
                       &property,
                       sizeof(property),
                       &value,
                       sizeof(value),
                       &returned)) {
    return std::nullopt;
  }
  return value;
}

struct KsDataRangeInfo {
  KSDATARANGE_AUDIO audio{};
  bool audio_range = false;
  std::string specifier;
  std::string sub_format;
};

std::size_t AlignUp8(std::size_t value) {
  return (value + 7u) & ~static_cast<std::size_t>(7u);
}

std::vector<KsDataRangeInfo> QueryPinDataRanges(HANDLE filter,
                                                ULONG pin_id,
                                                ApiErrorInfo* error) {
  KSP_PIN property{};
  property.Property.Set = KSPROPSETID_Pin;
  property.Property.Id = KSPROPERTY_PIN_DATARANGES;
  property.Property.Flags = KSPROPERTY_TYPE_GET;
  property.PinId = pin_id;

  std::vector<std::byte> buffer(kMaxKernelStreamingDataRangeBytes);
  DWORD returned = 0;
  if (!QueryKsProperty(filter,
                       &property,
                       sizeof(property),
                       buffer.data(),
                       static_cast<DWORD>(buffer.size()),
                       &returned)) {
    if (error != nullptr) {
      *error = MakeApiErrorForDomain(
          Win32Code(GetLastError()),
          "KSPROPERTY_PIN_DATARANGES",
          "failed to query Kernel Streaming pin data ranges",
          "win32");
    }
    return {};
  }
  if (returned < sizeof(KSMULTIPLE_ITEM)) {
    if (error != nullptr) {
      *error = MakeApiError(0,
                            "KSPROPERTY_PIN_DATARANGES_SHORT_READ",
                            "pin data range query returned too few bytes");
    }
    return {};
  }

  const auto* multiple =
      reinterpret_cast<const KSMULTIPLE_ITEM*>(buffer.data());
  const auto total_size = std::min<std::size_t>(
      static_cast<std::size_t>(multiple->Size),
      static_cast<std::size_t>(returned));
  std::size_t offset = sizeof(KSMULTIPLE_ITEM);
  std::vector<KsDataRangeInfo> ranges;
  const auto count = std::min<std::uint32_t>(
      multiple->Count,
      kMaxKernelStreamingDataRanges);
  for (std::uint32_t index = 0; index < count; ++index) {
    if (offset + sizeof(KSDATARANGE) > total_size) {
      break;
    }
    const auto* range =
        reinterpret_cast<const KSDATARANGE*>(buffer.data() + offset);
    if (range->FormatSize < sizeof(KSDATARANGE) ||
        offset + range->FormatSize > total_size) {
      break;
    }
    KsDataRangeInfo info;
    info.specifier = SpecifierName(range->Specifier);
    info.sub_format = SubFormatName(range->SubFormat);
    if (range->FormatSize >= sizeof(KSDATARANGE_AUDIO) &&
        IsEqualGUID(range->MajorFormat, KSDATAFORMAT_TYPE_AUDIO)) {
      info.audio = *reinterpret_cast<const KSDATARANGE_AUDIO*>(range);
      info.audio_range = true;
    }
    ranges.push_back(std::move(info));
    offset = AlignUp8(offset + range->FormatSize);
  }
  return ranges;
}

bool IsIntegerPcm(const FormatDescriptor& format) {
  return format.sample_type == SampleType::kInt16 ||
         format.sample_type == SampleType::kInt24Packed ||
         format.sample_type == SampleType::kInt24In32 ||
         format.sample_type == SampleType::kInt32;
}

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

bool DataRangeMayAcceptFormat(const KsDataRangeInfo& info,
                              const FormatDescriptor& format) {
  if (!info.audio_range ||
      (format.signal_mode != SignalMode::kPcm &&
       format.signal_mode != SignalMode::kDop)) {
    return false;
  }
  const auto& range = info.audio;
  if (!(IsEqualGUID(range.DataRange.SubFormat, KSDATAFORMAT_SUBTYPE_WILDCARD) ||
        (IsIntegerPcm(format) &&
         IsEqualGUID(range.DataRange.SubFormat, KSDATAFORMAT_SUBTYPE_PCM)) ||
        (IsFloatPcm(format) &&
         IsEqualGUID(range.DataRange.SubFormat,
                     KSDATAFORMAT_SUBTYPE_IEEE_FLOAT)))) {
    return false;
  }
  if (!(IsEqualGUID(range.DataRange.Specifier, KSDATAFORMAT_SPECIFIER_WILDCARD) ||
        IsEqualGUID(range.DataRange.Specifier,
                    KSDATAFORMAT_SPECIFIER_WAVEFORMATEX) ||
        IsEqualGUID(range.DataRange.Specifier, KSDATAFORMAT_SPECIFIER_DSOUND))) {
    return false;
  }
  if (range.MaximumChannels != 0 &&
      format.channels.channel_count > range.MaximumChannels) {
    return false;
  }
  if (format.sample_rate_hz < range.MinimumSampleFrequency ||
      format.sample_rate_hz > range.MaximumSampleFrequency) {
    return false;
  }
  const auto requested_bits = format.container_bits_per_sample;
  return requested_bits >= range.MinimumBitsPerSample &&
         requested_bits <= range.MaximumBitsPerSample;
}

std::optional<std::size_t> MatchingRangeIndex(
    const std::vector<KsDataRangeInfo>& ranges,
    const FormatDescriptor& format) {
  for (std::size_t index = 0; index < ranges.size(); ++index) {
    if (DataRangeMayAcceptFormat(ranges[index], format)) {
      return index;
    }
  }
  return std::nullopt;
}

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

CapabilityProbeRecord TryCreatePinForFormat(HANDLE filter,
                                            ULONG pin_id,
                                            const FormatDescriptor& format,
                                            const KSPIN_INTERFACE& pin_interface,
                                            const KSPIN_MEDIUM& pin_medium,
                                            bool allow_wavert_buffer_probe =
                                                false) {
  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.Flags = 0;
  request.data_format.SampleSize =
      (format.channels.channel_count * format.container_bits_per_sample) / 8;
  request.data_format.Reserved = 0;
  request.data_format.MajorFormat = KSDATAFORMAT_TYPE_AUDIO;
  request.data_format.SubFormat = IsFloatPcm(format)
      ? KSDATAFORMAT_SUBTYPE_IEEE_FLOAT
      : KSDATAFORMAT_SUBTYPE_PCM;
  request.data_format.Specifier = KSDATAFORMAT_SPECIFIER_WAVEFORMATEX;
  request.wave_format = WaveFormatFromDescriptor(format);

  using KsCreatePinFn = DWORD(WINAPI*)(HANDLE, PKSPIN_CONNECT, ACCESS_MASK,
                                       PHANDLE);
  HMODULE ksuser = LoadLibraryW(L"ksuser.dll");
  if (ksuser == nullptr) {
    auto error = MakeApiErrorForDomain(Win32Code(GetLastError()),
                                       "LoadLibrary(ksuser.dll)",
                                       "failed to load ksuser.dll",
                                       "win32");
    auto record = MakeKernelStreamingFormatProbeRecord(
        format,
        CapabilitySupport::kFailed,
        "ksuser.dll is not available for non-playback pin creation probe");
    record.error = error;
    AddErrorEvidence(record.backend_fields, error, "win32");
    record.backend_fields["creates_pin"] = "false";
    record.backend_fields["ks_result_level"] = "error";
    return record;
  }
  const auto create_pin = reinterpret_cast<KsCreatePinFn>(
      GetProcAddress(ksuser, "KsCreatePin"));
  if (create_pin == nullptr) {
    const auto last_error = GetLastError();
    FreeLibrary(ksuser);
    auto record = MakeKernelStreamingFormatProbeRecord(
        format,
        CapabilitySupport::kFailed,
        "KsCreatePin entry point is unavailable");
    auto error = MakeApiErrorForDomain(Win32Code(last_error),
                                       "GetProcAddress(KsCreatePin)",
                                       "failed to resolve KsCreatePin",
                                       "win32");
    record.error = error;
    AddErrorEvidence(record.backend_fields, error, "win32");
    record.backend_fields["creates_pin"] = "false";
    record.backend_fields["ks_result_level"] = "error";
    return record;
  }

  ScopedHandle pin;
  const DWORD status =
      create_pin(filter, &request.connect, GENERIC_WRITE, pin.put());
  FreeLibrary(ksuser);
  const bool pin_created =
      status == ERROR_SUCCESS && pin.valid();
  auto record = MakeKernelStreamingFormatProbeRecord(
      format,
      KernelStreamingSupportFromNtStatus(NtStatusCode(static_cast<LONG>(status))),
      pin_created
          ? "Kernel Streaming pin accepted exact PCM/DoP carrier format; pin closed immediately without setting RUN"
          : "Kernel Streaming pin creation probe rejected or failed exact PCM/DoP carrier format");
  record.backend_fields["creates_pin"] = "true";
  record.backend_fields["ks_pin_interface"] =
      KernelStreamingInterfaceLabel(pin_interface);
  record.backend_fields["ks_pin_medium"] =
      KernelStreamingMediumLabel(pin_medium);
  record.backend_fields["ks_result_level"] =
      pin_created ? "pin_create_verified" : "error";
  record.backend_fields["ks_create_pin_ntstatus"] =
      HexCode32ForDomain(NtStatusCode(static_cast<LONG>(status)), "ntstatus");
  record.backend_fields["ks_pin_state_run"] = "false";
  if (pin_created) {
    const bool wavert_basic = DetectWaveRtRtAudioBasicSupport(pin.get());
    const bool wavert_notification =
        allow_wavert_buffer_probe &&
        ProbeWaveRtNotificationBuffer(pin.get(), format);
    record.backend_fields["supports_wavert_rtaudio_properties"] =
        (wavert_basic || wavert_notification) ? "true" : "false";
    record.backend_fields["accepts_wavert_notification_buffer"] =
        wavert_notification ? "true"
                            : (allow_wavert_buffer_probe ? "false"
                                                         : "unknown");
    record.backend_fields["ks_wavert_detection_method"] =
        allow_wavert_buffer_probe
            ? "KSPROPSETID_RtAudio BASICSUPPORT or BUFFER_WITH_NOTIFICATION probe"
            : "KSPROPSETID_RtAudio BASICSUPPORT";
  }
  if (!pin_created) {
    auto error = MakeApiErrorForDomain(
        NtStatusCode(static_cast<LONG>(status)),
        KernelStreamingStatusSymbol(NtStatusCode(static_cast<LONG>(status))),
        "KsCreatePin returned a non-success status",
        "ntstatus");
    record.error = error;
    AddErrorEvidence(record.backend_fields, error, "ntstatus");
  }
  return record;
}

std::string DevicePropertyString(HDEVINFO info,
                                 SP_DEVINFO_DATA* data,
                                 DWORD property) {
  wchar_t buffer[512]{};
  if (SetupDiGetDeviceRegistryPropertyW(info,
                                        data,
                                        property,
                                        nullptr,
                                        reinterpret_cast<PBYTE>(buffer),
                                        sizeof(buffer),
                                        nullptr)) {
    return WideToUtf8(buffer);
  }
  return {};
}

void AddPinSnapshot(std::vector<DeviceCapabilitySnapshot>& devices,
                    const std::string& filter_path,
                    const std::string& filter_name,
                    ULONG pin_id,
                    KSPIN_DATAFLOW dataflow,
                    KSPIN_COMMUNICATION communication,
                    const std::vector<KSPIN_INTERFACE>& pin_interfaces,
                    const std::vector<KSPIN_MEDIUM>& pin_mediums,
                    const std::vector<KsDataRangeInfo>& ranges) {
  auto snapshot = MakeKernelStreamingPinSnapshot(
      filter_path,
      pin_id,
      PinDataflowName(dataflow),
      PinCommunicationName(communication),
      static_cast<std::uint32_t>(ranges.size()),
      IsKernelStreamingRenderPlaybackPin(dataflow, communication)
          ? DeviceAvailability::kActive
          : DeviceAvailability::kUnavailable);
  snapshot.device.display_name = filter_name.empty()
      ? snapshot.device.display_name
      : filter_name;
  snapshot.backend_fields["ks_pin_dataflow_raw"] =
      std::to_string(static_cast<int>(dataflow));
  snapshot.backend_fields["ks_pin_communication_raw"] =
      std::to_string(static_cast<int>(communication));
  snapshot.backend_fields["ks_render_candidate"] =
      IsKernelStreamingRenderPlaybackPin(dataflow, communication) ? "true"
                                                                  : "false";
  const auto model = ClassifyKernelStreamingModel(pin_interfaces, "unknown");
  AddKernelStreamingModelFields(snapshot.backend_fields, model);
  if (const auto selected_interface =
          SelectKernelStreamingPlaybackInterface(pin_interfaces)) {
    snapshot.backend_fields["ks_pin_interface"] =
        KernelStreamingInterfaceLabel(*selected_interface);
  }
  snapshot.backend_fields["ks_pin_medium"] =
      KernelStreamingMediumLabel(SelectKernelStreamingPinMedium(pin_mediums));
  if (!ranges.empty()) {
    snapshot.backend_fields["ks_data_format_specifier"] =
        ranges.front().specifier;
    snapshot.backend_fields["ks_data_format_subtype"] =
        ranges.front().sub_format;
    const auto& first = ranges.front();
    if (first.audio_range) {
      snapshot.backend_fields["ks_range_min_sample_rate_hz"] =
          std::to_string(first.audio.MinimumSampleFrequency);
      snapshot.backend_fields["ks_range_max_sample_rate_hz"] =
          std::to_string(first.audio.MaximumSampleFrequency);
      snapshot.backend_fields["ks_range_min_bits"] =
          std::to_string(first.audio.MinimumBitsPerSample);
      snapshot.backend_fields["ks_range_max_bits"] =
          std::to_string(first.audio.MaximumBitsPerSample);
      snapshot.backend_fields["ks_range_max_channels"] =
          std::to_string(first.audio.MaximumChannels);
    }
  }

  CapabilityProbeRecord probe;
  probe.kind = CapabilityProbeKind::kDiscoveryOnly;
  probe.support = IsKernelStreamingRenderPlaybackPin(dataflow, communication)
      ? CapabilitySupport::kSupported
      : CapabilitySupport::kUnsupported;
  probe.detail =
      IsKernelStreamingRenderPlaybackPin(dataflow, communication)
          ? "Kernel Streaming render/sink playback pin discovered; no stream was started"
          : "Kernel Streaming non-playback pin discovered; not selectable for playback";
  probe.backend_fields = snapshot.backend_fields;
  devices.push_back(std::move(snapshot));
}

#endif

}  // namespace

KernelStreamingStreamingModelMetadata ClassifyKernelStreamingStreamingModel(
    bool supports_standard_streaming,
    bool supports_looped_streaming,
    std::string supports_wavert_rtaudio_properties,
    std::string pin_interface_set,
    std::string pin_interface_id,
    std::string accepts_wavert_notification_buffer) {
  KernelStreamingStreamingModelMetadata metadata;
  metadata.supports_standard_streaming = supports_standard_streaming;
  metadata.supports_looped_streaming = supports_looped_streaming;
  metadata.supports_wavert_rtaudio_properties =
      std::move(supports_wavert_rtaudio_properties);
  metadata.accepts_wavert_notification_buffer =
      std::move(accepts_wavert_notification_buffer);
  metadata.pin_interface_set = std::move(pin_interface_set);
  metadata.pin_interface_id = std::move(pin_interface_id);

  if (metadata.accepts_wavert_notification_buffer == "true" &&
      metadata.supports_looped_streaming) {
    metadata.streaming_model = "wavert_cyclic";
    metadata.playback_implementation = "implemented";
  } else if (metadata.supports_standard_streaming) {
    metadata.streaming_model = "standard_packet";
    metadata.playback_implementation = "implemented";
  } else if (metadata.supports_looped_streaming) {
    metadata.streaming_model = "standard_looped";
  }
  return metadata;
}

FormatDescriptor KernelStreamingPcmCandidate(std::uint32_t sample_rate_hz,
                                             SampleType sample_type,
                                             std::uint32_t channel_count) {
  FormatDescriptor descriptor;
  descriptor.signal_mode = SignalMode::kPcm;
  descriptor.sample_rate_hz = sample_rate_hz;
  descriptor.sample_type = sample_type;
  descriptor.channels.channel_count = channel_count;
  descriptor.channels.channel_mask = channel_count == 2 ? 3 : 0;
  switch (sample_type) {
    case SampleType::kInt16:
      descriptor.valid_bits_per_sample = 16;
      descriptor.container_bits_per_sample = 16;
      break;
    case SampleType::kInt24Packed:
      descriptor.valid_bits_per_sample = 24;
      descriptor.container_bits_per_sample = 24;
      break;
    case SampleType::kInt24In32:
      descriptor.valid_bits_per_sample = 24;
      descriptor.container_bits_per_sample = 32;
      break;
    case SampleType::kInt32:
      descriptor.valid_bits_per_sample = 32;
      descriptor.container_bits_per_sample = 32;
      break;
    case SampleType::kFloat32:
    default:
      descriptor.sample_type = SampleType::kFloat32;
      descriptor.valid_bits_per_sample = 32;
      descriptor.container_bits_per_sample = 32;
      break;
  }
  return descriptor;
}

std::vector<FormatDescriptor> KernelStreamingDefaultPcmCandidates() {
  constexpr std::uint32_t kSampleRatesHz[] = {
      44100, 48000, 88200, 96000, 176400, 192000, 352800,
      384000, 705600, 768000, 786000, 1411200, 1536000};
  constexpr SampleType kSampleTypes[] = {
      SampleType::kInt16,
      SampleType::kInt24Packed,
      SampleType::kInt24In32,
      SampleType::kFloat32,
      SampleType::kInt32,
  };

  std::vector<FormatDescriptor> candidates;
  candidates.reserve(std::size(kSampleRatesHz) * std::size(kSampleTypes));
  for (const auto sample_rate_hz : kSampleRatesHz) {
    for (const auto sample_type : kSampleTypes) {
      candidates.push_back(
          KernelStreamingPcmCandidate(sample_rate_hz, sample_type, 2));
    }
  }
  return candidates;
}

std::string KernelStreamingStableId(std::string filter_symbolic_link,
                                    std::uint32_t pin_id) {
  return "ks:" + std::move(filter_symbolic_link) +
         "#pin:" + std::to_string(pin_id);
}

std::optional<KernelStreamingStableIdParts> ParseKernelStreamingStableId(
    const std::string& stable_id) {
  constexpr std::string_view kPrefix = "ks:";
  constexpr std::string_view kPinMarker = "#pin:";
  if (stable_id.rfind(kPrefix, 0) != 0) {
    return std::nullopt;
  }
  const auto marker = stable_id.rfind(kPinMarker);
  if (marker == std::string::npos || marker <= kPrefix.size()) {
    return std::nullopt;
  }
  const std::string filter = stable_id.substr(kPrefix.size(),
                                             marker - kPrefix.size());
  const std::string pin_text = stable_id.substr(marker + kPinMarker.size());
  if (filter.empty() || pin_text.empty()) {
    return std::nullopt;
  }
  std::uint64_t pin_value = 0;
  for (const char ch : pin_text) {
    if (ch < '0' || ch > '9') {
      return std::nullopt;
    }
    pin_value = (pin_value * 10u) + static_cast<unsigned>(ch - '0');
    if (pin_value > UINT32_MAX) {
      return std::nullopt;
    }
  }
  return KernelStreamingStableIdParts{
      .filter_symbolic_link = filter,
      .pin_id = static_cast<std::uint32_t>(pin_value),
  };
}

std::string KernelStreamingStatusSymbol(std::int64_t raw_status) {
  const auto status = static_cast<std::uint32_t>(raw_status);
  if (raw_status == 0) {
    return "STATUS_SUCCESS";
  }
  if (status == 0xC000000Du) {
    return "STATUS_INVALID_PARAMETER";
  }
  if (status == 0xC0000010u) {
    return "STATUS_INVALID_DEVICE_REQUEST";
  }
  if (status == 0xC00000BBu) {
    return "STATUS_NOT_SUPPORTED";
  }
  if (status == 0xC00000EFu) {
    return "STATUS_INVALID_PARAMETER_MIX";
  }
  if (status == 0xC0000184u) {
    return "STATUS_INVALID_DEVICE_STATE";
  }
  return "NTSTATUS";
}

CapabilitySupport KernelStreamingSupportFromNtStatus(
    std::int64_t raw_status) {
  if (raw_status == 0) {
    return CapabilitySupport::kSupported;
  }
  const auto status = static_cast<std::uint32_t>(raw_status);
  if (status == 0xC000000Du || status == 0xC0000010u ||
      status == 0xC00000BBu || status == 0xC00000EFu) {
    return CapabilitySupport::kUnsupported;
  }
  return CapabilitySupport::kFailed;
}

DeviceCapabilitySnapshot MakeKernelStreamingPinSnapshot(
    std::string filter_symbolic_link,
    std::uint32_t pin_id,
    std::string dataflow,
    std::string communication,
    std::uint32_t data_range_count,
    DeviceAvailability availability) {
  DeviceInfo device;
  device.backend = BackendApi::kKernelStreaming;
  device.display_name = "Kernel Streaming output";
  device.stable_id = KernelStreamingStableId(filter_symbolic_link, pin_id);
  device.driver_name = "KS/AVStream";

  auto snapshot = MakeDiscoveredDeviceSnapshot(std::move(device), availability);
  snapshot.backend_fields["api"] = "Kernel Streaming";
  snapshot.backend_fields["api_device_id"] =
      snapshot.device.stable_id;
  snapshot.backend_fields["id_kind"] = "ks-filter-symbolic-link-pin";
  snapshot.backend_fields["ks_filter_symbolic_link"] =
      std::move(filter_symbolic_link);
  snapshot.backend_fields["ks_pin_id"] = std::to_string(pin_id);
  snapshot.backend_fields["ks_pin_label"] =
      "output pin " + std::to_string(pin_id);
  snapshot.backend_fields["ks_pin_dataflow"] = std::move(dataflow);
  snapshot.backend_fields["ks_pin_communication"] =
      std::move(communication);
  snapshot.backend_fields["ks_data_range_count"] =
      std::to_string(data_range_count);
  snapshot.backend_fields["ks_data_format_specifier"] =
      data_range_count == 0 ? "none" : "not-summarized";
  snapshot.backend_fields["opens_filter"] = "true";
  snapshot.backend_fields["creates_pin"] = "false";
  snapshot.backend_fields["initializes_stream"] = "false";
  snapshot.backend_fields["starts_stream"] = "false";
  return snapshot;
}

DiscoverySnapshot EnumerateKernelStreamingDevices() {
  DiscoverySnapshot snapshot;
  snapshot.backend = BackendApi::kKernelStreaming;
  snapshot.opens_audio_device = false;
  snapshot.initializes_stream = false;
  snapshot.starts_stream = false;

#if !defined(APTT_HAS_WINDOWS_KS_HEADERS)
  snapshot.enumeration_error = MakeApiErrorForDomain(
      kHresultNotImplemented,
      "E_NOTIMPL",
      "Kernel Streaming discovery requires Windows KS and SetupAPI headers",
      "hresult");
  return snapshot;
#else
  ScopedDeviceInfoSet info(SetupDiGetClassDevsW(&KSCATEGORY_AUDIO,
                                                nullptr,
                                                nullptr,
                                                DIGCF_PRESENT |
                                                    DIGCF_DEVICEINTERFACE));
  if (!info.valid()) {
    snapshot.enumeration_error = MakeApiErrorForDomain(
        Win32Code(GetLastError()),
        "SetupDiGetClassDevs(KSCATEGORY_AUDIO)",
        "failed to enumerate Kernel Streaming audio device interfaces",
        "win32");
    return snapshot;
  }

  for (DWORD index = 0; index < kMaxKernelStreamingFilters; ++index) {
    SP_DEVICE_INTERFACE_DATA interface_data{};
    interface_data.cbSize = sizeof(interface_data);
    if (!SetupDiEnumDeviceInterfaces(info.get(),
                                     nullptr,
                                     &KSCATEGORY_AUDIO,
                                     index,
                                     &interface_data)) {
      if (GetLastError() == ERROR_NO_MORE_ITEMS) {
        break;
      }
      continue;
    }

    DWORD required_size = 0;
    SP_DEVINFO_DATA device_info{};
    device_info.cbSize = sizeof(device_info);
    SetupDiGetDeviceInterfaceDetailW(info.get(),
                                     &interface_data,
                                     nullptr,
                                     0,
                                     &required_size,
                                     &device_info);
    if (required_size == 0) {
      continue;
    }
    std::vector<std::byte> detail_storage(required_size);
    auto* detail = reinterpret_cast<SP_DEVICE_INTERFACE_DETAIL_DATA_W*>(
        detail_storage.data());
    detail->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA_W);
    if (!SetupDiGetDeviceInterfaceDetailW(
            info.get(),
            &interface_data,
            detail,
            required_size,
            nullptr,
            &device_info)) {
      continue;
    }

    const std::string filter_path = WideToUtf8(detail->DevicePath);
    std::string filter_name =
        DevicePropertyString(info.get(), &device_info, SPDRP_FRIENDLYNAME);
    if (filter_name.empty()) {
      filter_name =
          DevicePropertyString(info.get(), &device_info, SPDRP_DEVICEDESC);
    }
    if (filter_name.empty()) {
      filter_name = "Kernel Streaming filter " + std::to_string(index);
    }

    constexpr DWORD requested_access = GENERIC_READ;
    ScopedHandle filter(CreateFileW(detail->DevicePath,
                                    requested_access,
                                    FILE_SHARE_READ | FILE_SHARE_WRITE,
                                    nullptr,
                                    OPEN_EXISTING,
                                    FILE_ATTRIBUTE_NORMAL,
                                    nullptr));
    if (!filter.valid()) {
      DeviceInfo device;
      device.backend = BackendApi::kKernelStreaming;
      device.display_name = filter_name;
      device.stable_id = KernelStreamingStableId(filter_path, 0);
      device.driver_name = "KS/AVStream";
      auto failure = MakeDiscoveredDeviceSnapshot(
          std::move(device),
          DeviceAvailability::kUnavailable);
      auto error = MakeApiErrorForDomain(
          Win32Code(GetLastError()),
          "CreateFile(KernelStreamingFilter)",
          "failed to open KS filter for bounded pin discovery",
          "win32");
      failure.discovery_error = error;
      failure.backend_fields["ks_filter_symbolic_link"] = filter_path;
      failure.backend_fields["ks_pin_id"] = "not-enumerated";
      failure.backend_fields["opens_filter"] = "true";
      failure.backend_fields["requested_access"] =
          AccessMaskLabel(requested_access);
      failure.backend_fields["event_category"] = "discovery";
      AddErrorEvidence(failure.backend_fields, error, "win32");
      failure.backend_fields["creates_pin"] = "false";
      failure.backend_fields["starts_stream"] = "false";
      snapshot.devices.push_back(std::move(failure));
      continue;
    }
    snapshot.opens_audio_device = true;

    const auto pin_count = QueryPinCount(filter.get());
    if (!pin_count) {
      DeviceInfo device;
      device.backend = BackendApi::kKernelStreaming;
      device.display_name = filter_name;
      device.stable_id = KernelStreamingStableId(filter_path, 0);
      device.driver_name = "KS/AVStream";
      auto failure = MakeDiscoveredDeviceSnapshot(
          std::move(device),
          DeviceAvailability::kUnavailable);
      failure.discovery_error = MakeApiErrorForDomain(
          Win32Code(GetLastError()),
          "KSPROPERTY_PIN_CTYPES",
          "failed to query KS pin count",
          "win32");
      failure.backend_fields["ks_filter_symbolic_link"] = filter_path;
      failure.backend_fields["ks_pin_id"] = "not-enumerated";
      failure.backend_fields["opens_filter"] = "true";
      failure.backend_fields["requested_access"] =
          AccessMaskLabel(requested_access);
      failure.backend_fields["event_category"] = "discovery";
      AddErrorEvidence(failure.backend_fields,
                       *failure.discovery_error,
                       "win32");
      failure.backend_fields["creates_pin"] = "false";
      failure.backend_fields["starts_stream"] = "false";
      snapshot.devices.push_back(std::move(failure));
      continue;
    }

    const auto bounded_pin_count = std::min<ULONG>(
        *pin_count,
        kMaxKernelStreamingPinsPerFilter);
    for (ULONG pin_id = 0; pin_id < bounded_pin_count; ++pin_id) {
      const auto dataflow =
          QueryPinProperty<KSPIN_DATAFLOW>(filter.get(),
                                           pin_id,
                                           KSPROPERTY_PIN_DATAFLOW);
      const auto communication =
          QueryPinProperty<KSPIN_COMMUNICATION>(
              filter.get(),
              pin_id,
              KSPROPERTY_PIN_COMMUNICATION);
      if (!dataflow || !communication) {
        continue;
      }
      const auto pin_interfaces =
          QueryPinPropertyArray<KSPIN_INTERFACE>(
              filter.get(),
              pin_id,
              KSPROPERTY_PIN_INTERFACES);
      const auto pin_mediums =
          QueryPinPropertyArray<KSPIN_MEDIUM>(
              filter.get(),
              pin_id,
              KSPROPERTY_PIN_MEDIUMS);
      ApiErrorInfo data_range_error;
      auto ranges = QueryPinDataRanges(filter.get(),
                                       pin_id,
                                       &data_range_error);
      AddPinSnapshot(snapshot.devices,
                     filter_path,
                     filter_name,
                     pin_id,
                     *dataflow,
                     *communication,
                     pin_interfaces,
                     pin_mediums,
                     ranges);
      auto& added = snapshot.devices.back();
      added.backend_fields["requested_access"] =
          AccessMaskLabel(requested_access);
      added.backend_fields["event_category"] = "discovery";
      if (ranges.empty()) {
        added.discovery_error = data_range_error;
        AddErrorEvidence(added.backend_fields, data_range_error, "win32");
      }
    }
  }

  if (snapshot.devices.empty()) {
    snapshot.enumeration_error = MakeApiError(
        0,
        "APTT_KS_NO_FILTER_PINS",
        "no Kernel Streaming audio filter pins were discovered");
  }
  return snapshot;
#endif
}

DeviceCapabilitySnapshot ProbeKernelStreamingPinFormats(
    const KernelStreamingFormatProbeRequest& request) {
  const auto parsed = ParseKernelStreamingStableId(request.stable_id);
  if (!parsed) {
    return MakeKernelStreamingFailure(
        request.stable_id,
        MakeApiErrorForDomain(kHresultInvalidArg,
                              "E_INVALIDARG",
                              "Kernel Streaming format probe requires a ks:<filter>#pin:<id> stable ID",
                              "hresult"));
  }

#if !defined(APTT_HAS_WINDOWS_KS_HEADERS)
  return MakeKernelStreamingFailure(
      request.stable_id,
      MakeApiErrorForDomain(
          kHresultNotImplemented,
          "E_NOTIMPL",
          "Kernel Streaming format probe requires Windows KS and SetupAPI headers",
          "hresult"));
#else
  const std::wstring filter_path = Utf8ToWide(parsed->filter_symbolic_link);
  const bool needs_pin_probe_access =
      request.create_pin_for_exact_format ||
      request.detect_wavert_with_pin_probe;
  const DWORD requested_access = needs_pin_probe_access
      ? (GENERIC_READ | GENERIC_WRITE)
      : GENERIC_READ;
  ScopedHandle filter(CreateFileW(filter_path.c_str(),
                                  requested_access,
                                  FILE_SHARE_READ | FILE_SHARE_WRITE,
                                  nullptr,
                                  OPEN_EXISTING,
                                  FILE_ATTRIBUTE_NORMAL,
                                  nullptr));
  if (!filter.valid()) {
    auto failure = MakeKernelStreamingFailure(
        request.stable_id,
        MakeApiErrorForDomain(
            Win32Code(GetLastError()),
            "CreateFile(KernelStreamingFilter)",
            "failed to open selected KS filter for pin format probe",
            "win32"));
    failure.backend_fields["requested_access"] =
        AccessMaskLabel(requested_access);
    failure.backend_fields["event_category"] = "probe";
    if (failure.discovery_error) {
      AddErrorEvidence(failure.backend_fields,
                       *failure.discovery_error,
                       "win32");
    }
    return failure;
  }

  const auto dataflow =
      QueryPinProperty<KSPIN_DATAFLOW>(filter.get(),
                                       parsed->pin_id,
                                       KSPROPERTY_PIN_DATAFLOW);
  const auto communication =
      QueryPinProperty<KSPIN_COMMUNICATION>(
          filter.get(),
                                          parsed->pin_id,
                                          KSPROPERTY_PIN_COMMUNICATION);
  const bool render_playback_candidate =
      dataflow && communication &&
      IsKernelStreamingRenderPlaybackPin(*dataflow, *communication);
  const auto pin_interfaces =
      QueryPinPropertyArray<KSPIN_INTERFACE>(
          filter.get(),
          parsed->pin_id,
          KSPROPERTY_PIN_INTERFACES);
  const auto pin_mediums =
      QueryPinPropertyArray<KSPIN_MEDIUM>(
          filter.get(),
          parsed->pin_id,
          KSPROPERTY_PIN_MEDIUMS);
  const bool standard_streaming_supported =
      std::any_of(pin_interfaces.begin(),
                  pin_interfaces.end(),
                  IsKernelStreamingStandardStreamingInterface);
  const bool looped_streaming_supported =
      std::any_of(pin_interfaces.begin(),
                  pin_interfaces.end(),
                  IsKernelStreamingLoopedStreamingInterface);
  auto model =
      ClassifyKernelStreamingModel(pin_interfaces, "unknown");
  const auto selected_interface =
      SelectKernelStreamingPlaybackInterface(pin_interfaces);
  const auto wavert_probe_interface =
      SelectKernelStreamingWaveRtProbeInterface(pin_interfaces);
  const auto selected_medium = SelectKernelStreamingPinMedium(pin_mediums);
  const bool streaming_interface_detected =
      standard_streaming_supported || looped_streaming_supported;
  const bool format_probe_candidate =
      render_playback_candidate && streaming_interface_detected;
  ApiErrorInfo data_range_error;
  auto ranges = QueryPinDataRanges(filter.get(),
                                   parsed->pin_id,
                                   &data_range_error);

  auto snapshot = MakeKernelStreamingPinSnapshot(
      parsed->filter_symbolic_link,
      parsed->pin_id,
      dataflow ? PinDataflowName(*dataflow) : "unknown",
      communication ? PinCommunicationName(*communication) : "unknown",
      static_cast<std::uint32_t>(ranges.size()),
      dataflow && *dataflow == KSPIN_DATAFLOW_IN
          ? DeviceAvailability::kActive
          : DeviceAvailability::kUnavailable);
  snapshot.device.display_name = "Selected Kernel Streaming pin";
  snapshot.backend_fields["bounded_candidate_count"] =
      std::to_string(request.max_candidate_formats);
  snapshot.backend_fields["ks_pin_state_run"] = "false";
  snapshot.backend_fields["ks_render_candidate"] =
      render_playback_candidate ? "true" : "false";
  AddKernelStreamingModelFields(snapshot.backend_fields, model);
  if (selected_interface) {
    snapshot.backend_fields["ks_pin_interface"] =
        KernelStreamingInterfaceLabel(*selected_interface);
  }
  snapshot.backend_fields["ks_pin_medium"] =
      KernelStreamingMediumLabel(selected_medium);
  if (dataflow) {
    snapshot.backend_fields["ks_pin_dataflow_raw"] =
        std::to_string(static_cast<int>(*dataflow));
  }
  if (communication) {
    snapshot.backend_fields["ks_pin_communication_raw"] =
        std::to_string(static_cast<int>(*communication));
  }
  snapshot.backend_fields["requested_access"] =
      AccessMaskLabel(requested_access);
  snapshot.backend_fields["event_category"] = "probe";
  snapshot.backend_fields["pin_create_probe_requested"] =
      request.create_pin_for_exact_format ? "true" : "false";
  snapshot.backend_fields["wavert_detection_pin_probe_requested"] =
      request.detect_wavert_with_pin_probe ? "true" : "false";
  snapshot.backend_fields["requested_access_reason"] =
      request.create_pin_for_exact_format
          ? "pin creation probe requires write access for KsCreatePin"
          : request.detect_wavert_with_pin_probe
                ? "WaveRT detection probe creates one pin without RUN"
                : "data-range query path uses read-only access";
  if (!ranges.empty()) {
    snapshot.backend_fields["ks_data_format_specifier"] =
        ranges.front().specifier;
    snapshot.backend_fields["ks_data_format_subtype"] =
        ranges.front().sub_format;
  } else {
    snapshot.discovery_error = data_range_error;
  }

  std::vector<FormatDescriptor> candidates;
  candidates.reserve(std::min<std::size_t>(request.candidate_formats.size(),
                                           request.max_candidate_formats));
  for (const auto& candidate : request.candidate_formats) {
    if (candidates.size() >= request.max_candidate_formats) {
      break;
    }
    if (candidate.signal_mode != SignalMode::kPcm &&
        candidate.signal_mode != SignalMode::kDop) {
      continue;
    }
    PushUniqueFormat(candidates, candidate);
  }
  if (candidates.empty()) {
    for (const auto& candidate : KernelStreamingDefaultPcmCandidates()) {
      if (candidates.size() >= request.max_candidate_formats) {
        break;
      }
      candidates.push_back(candidate);
    }
  }

  std::optional<std::string> wavert_detection_result;
  std::optional<std::string> wavert_notification_result;
  std::string wavert_detection_method;
  if (request.detect_wavert_with_pin_probe &&
      format_probe_candidate &&
      wavert_probe_interface) {
    for (const auto& candidate : candidates) {
      if (!MatchingRangeIndex(ranges, candidate)) {
        continue;
      }
      const auto detection_record =
          TryCreatePinForFormat(filter.get(),
                                parsed->pin_id,
                                candidate,
                                *wavert_probe_interface,
                                selected_medium,
                                true);
      std::this_thread::sleep_for(std::chrono::milliseconds(100));
      const auto wavert = detection_record.backend_fields.find(
          "supports_wavert_rtaudio_properties");
      if (wavert != detection_record.backend_fields.end()) {
        wavert_detection_result = wavert->second;
        const auto accepts = detection_record.backend_fields.find(
            "accepts_wavert_notification_buffer");
        if (accepts != detection_record.backend_fields.end()) {
          wavert_notification_result = accepts->second;
        }
        const auto method = detection_record.backend_fields.find(
            "ks_wavert_detection_method");
        wavert_detection_method =
            method != detection_record.backend_fields.end()
                ? method->second
                : "single KsCreatePin WaveRT probe";
        break;
      }
    }
  }
  if (wavert_detection_result) {
    model = ClassifyKernelStreamingModel(pin_interfaces,
                                         *wavert_detection_result,
                                         wavert_notification_result.value_or(
                                             "unknown"));
    AddKernelStreamingModelFields(snapshot.backend_fields, model);
    snapshot.backend_fields["ks_wavert_detection_method"] =
        wavert_detection_method;
    if (model.streaming_model == "wavert_cyclic" && wavert_probe_interface) {
      snapshot.backend_fields["ks_pin_interface"] =
          KernelStreamingInterfaceLabel(*wavert_probe_interface);
    }
  }
  const auto add_wavert_detection_fields =
      [&](std::map<std::string, std::string>& fields) {
    fields["wavert_buffer_probe_requested"] =
        request.detect_wavert_with_pin_probe ? "true" : "false";
    fields["wavert_buffer_probe"] = wavert_notification_result ? "true"
                                                               : "false";
    fields["wavert_detection_creates_pin"] =
        wavert_detection_result ? "true" : "false";
    fields["wavert_detection_starts_stream"] = "false";
    if (!wavert_detection_method.empty()) {
      fields["ks_wavert_detection_method"] = wavert_detection_method;
    }
  };
  add_wavert_detection_fields(snapshot.backend_fields);
  const auto interface_for_model =
      [&](const KernelStreamingStreamingModelMetadata& current_model)
      -> std::optional<KSPIN_INTERFACE> {
    if (current_model.streaming_model == "wavert_cyclic" &&
        wavert_probe_interface) {
      return wavert_probe_interface;
    }
    return selected_interface;
  };

  for (const auto& candidate : candidates) {
    if (!format_probe_candidate) {
      auto record = MakeKernelStreamingFormatProbeRecord(
          candidate,
          CapabilitySupport::kUnsupported,
          render_playback_candidate
              ? "Kernel Streaming selected pin does not expose a supported streaming interface"
              : "Kernel Streaming selected pin is not a render/sink playback pin");
      record.backend_fields["ks_filter_symbolic_link"] =
          parsed->filter_symbolic_link;
      record.backend_fields["ks_pin_id"] = std::to_string(parsed->pin_id);
      record.backend_fields["ks_pin_dataflow"] =
          dataflow ? PinDataflowName(*dataflow) : "unknown";
      record.backend_fields["ks_pin_communication"] =
          communication ? PinCommunicationName(*communication) : "unknown";
      record.backend_fields["ks_render_candidate"] =
          render_playback_candidate ? "true" : "false";
      AddKernelStreamingModelFields(record.backend_fields, model);
      add_wavert_detection_fields(record.backend_fields);
      const auto record_interface = interface_for_model(model);
      if (record_interface) {
        record.backend_fields["ks_pin_interface"] =
            KernelStreamingInterfaceLabel(*record_interface);
      }
      record.backend_fields["ks_pin_medium"] =
          KernelStreamingMediumLabel(selected_medium);
      record.backend_fields["opens_filter"] = "true";
      record.backend_fields["requested_access"] =
          AccessMaskLabel(requested_access);
      record.backend_fields["event_category"] = "probe";
      record.backend_fields["creates_pin"] = "false";
      record.backend_fields["starts_stream"] = "false";
      record.backend_fields["ks_result_level"] = "not_applicable";
      record.backend_fields["ks_data_range_count"] =
          std::to_string(ranges.size());
      snapshot.probes.push_back(std::move(record));
      continue;
    }

    const auto range_index = MatchingRangeIndex(ranges, candidate);
    if (!range_index) {
      auto record = MakeKernelStreamingFormatProbeRecord(
          candidate,
          CapabilitySupport::kUnsupported,
          "Kernel Streaming pin data ranges do not include this PCM/DoP carrier format");
      record.backend_fields["ks_filter_symbolic_link"] =
          parsed->filter_symbolic_link;
      record.backend_fields["ks_pin_id"] = std::to_string(parsed->pin_id);
      record.backend_fields["ks_pin_dataflow"] =
          dataflow ? PinDataflowName(*dataflow) : "unknown";
      record.backend_fields["ks_pin_communication"] =
          communication ? PinCommunicationName(*communication) : "unknown";
      record.backend_fields["ks_render_candidate"] =
          render_playback_candidate ? "true" : "false";
      AddKernelStreamingModelFields(record.backend_fields, model);
      add_wavert_detection_fields(record.backend_fields);
      const auto record_interface = interface_for_model(model);
      if (record_interface) {
        record.backend_fields["ks_pin_interface"] =
            KernelStreamingInterfaceLabel(*record_interface);
      }
      record.backend_fields["ks_pin_medium"] =
          KernelStreamingMediumLabel(selected_medium);
      record.backend_fields["opens_filter"] = "true";
      record.backend_fields["requested_access"] =
          AccessMaskLabel(requested_access);
      record.backend_fields["event_category"] = "probe";
      record.backend_fields["creates_pin"] = "false";
      record.backend_fields["ks_result_level"] = "unsupported";
      record.backend_fields["ks_data_range_count"] =
          std::to_string(ranges.size());
      snapshot.probes.push_back(std::move(record));
      continue;
    }

    CapabilityProbeRecord record =
        request.create_pin_for_exact_format
            ? TryCreatePinForFormat(filter.get(),
                                    parsed->pin_id,
                                    candidate,
                                    *selected_interface,
                                    selected_medium)
            : MakeKernelStreamingFormatProbeRecord(
                  candidate,
                  CapabilitySupport::kSupported,
                  "Kernel Streaming pin data range accepts PCM/DoP carrier format; exact pin creation disabled");
    record.backend_fields["ks_filter_symbolic_link"] =
        parsed->filter_symbolic_link;
    record.backend_fields["ks_pin_id"] = std::to_string(parsed->pin_id);
    record.backend_fields["ks_pin_dataflow"] =
        dataflow ? PinDataflowName(*dataflow) : "unknown";
    record.backend_fields["ks_pin_communication"] =
        communication ? PinCommunicationName(*communication) : "unknown";
    record.backend_fields["ks_render_candidate"] =
        render_playback_candidate ? "true" : "false";
    auto record_model = model;
    const auto wavert = record.backend_fields.find(
        "supports_wavert_rtaudio_properties");
    const auto accepts = record.backend_fields.find(
        "accepts_wavert_notification_buffer");
    if (wavert != record.backend_fields.end() ||
        accepts != record.backend_fields.end()) {
      record_model = ClassifyKernelStreamingModel(
          pin_interfaces,
          wavert != record.backend_fields.end() ? wavert->second : "unknown",
          accepts != record.backend_fields.end() ? accepts->second : "unknown");
    }
    AddKernelStreamingModelFields(record.backend_fields, record_model);
    add_wavert_detection_fields(record.backend_fields);
    if (record_model.playback_implementation == "unimplemented") {
      record.detail =
          "Kernel Streaming streaming model detected; playback is not implemented for this model yet";
    }
    const auto record_interface = interface_for_model(record_model);
    if (record_interface) {
      record.backend_fields["ks_pin_interface"] =
          KernelStreamingInterfaceLabel(*record_interface);
    }
    record.backend_fields["ks_pin_medium"] =
        KernelStreamingMediumLabel(selected_medium);
    record.backend_fields["ks_data_range_count"] =
        std::to_string(ranges.size());
    record.backend_fields["ks_matched_range_index"] =
        std::to_string(*range_index);
    record.backend_fields["ks_matched_subformat"] =
        ranges[*range_index].sub_format;
    record.backend_fields["ks_matched_specifier"] =
        ranges[*range_index].specifier;
    record.backend_fields["opens_filter"] = "true";
    record.backend_fields["requested_access"] =
        AccessMaskLabel(requested_access);
    record.backend_fields["event_category"] = "probe";
    if (!record.backend_fields.contains("ks_result_level")) {
      record.backend_fields["ks_result_level"] =
          request.create_pin_for_exact_format
              ? "pin_create_verified"
              : "data_range_match";
    }
    if (!record.backend_fields.contains("creates_pin")) {
      record.backend_fields["creates_pin"] =
          request.create_pin_for_exact_format ? "true" : "false";
    }
    record.backend_fields["starts_stream"] = "false";
    snapshot.probes.push_back(std::move(record));
  }

  return snapshot;
#endif
}

}  // namespace aptt
