Bring PS5 GTA6 to 120FPS with DLSS 5. An advanced Windows video player and capture enhancement tool featuring real-time preview for videos, images, and capture card sources. Combine AI-powered Super Resolution, DLSS5 image enhancement, and Frame Generation to deliver a next-generation visual experience.
C++
feat(dolby): Dolby/DTS bitstream passthrough to a receiver
Veyra Goal Agent275c3f28a222
diff --git a/CMakeLists.txt b/CMakeLists.txtindex d16b3774..05ccd689 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -153,6 +153,13 @@ add_executable(veyra_runtime_probetools/runtime_probe/main.cpp)+# Dolby/DTS endpoint passthrough capability probe (diagnostic, never shipped).+add_executable(veyra_bitstream_probe tools/bitstream_audio_probe/main.cpp)+target_compile_features(veyra_bitstream_probe PRIVATE cxx_std_20)+target_compile_options(veyra_bitstream_probe PRIVATE /utf-8 /WX-)+target_compile_definitions(veyra_bitstream_probe PRIVATE NOMINMAX WIN32_LEAN_AND_MEAN UNICODE _UNICODE)+target_link_libraries(veyra_bitstream_probe PRIVATE ole32)+# Isolated descriptor/Present diagnosis probe (user directive 2026-09-04 s3).# No NGX/FFmpeg/NVOF/WASAPI. Uses PresentBlit shaders for cases F/G.add_executable(veyra_descriptor_present_probe@@ -428,6 +435,7 @@ if(VEYRA_FFMPEG_ROOT AND EXISTS "${VEYRA_FFMPEG_ROOT}/include/libavformat/avformsrc/sink/CaptureAudioSession.cppsrc/sink/CaptureAudioDsp.cppsrc/sink/BitstreamAudio.cpp+ src/sink/BitstreamAudioSink.cppsrc/sink/ImageExportSink.cppsrc/sink/NvencD3D12Encoder.cpp)diff --git a/apps/veyra/ui/CapturePanel.cpp b/apps/veyra/ui/CapturePanel.cppindex 838469c4..35442396 100644--- a/apps/veyra/ui/CapturePanel.cpp+++ b/apps/veyra/ui/CapturePanel.cpp@@ -52,11 +52,11 @@ case WM_CREATE:{window=h;font=makeFont(h);titleTheme(h);auto add=[&](const wcharfor(auto name:{L"自动识别 SDR / HDR · 设备元数据",L"手动 HDR10 / PQ · BT.2020",L"手动 HLG · BT.2020 / 1000nit参考"})SendDlgItemMessageW(h,10,CB_ADDSTRING,0,LPARAM(name));SendDlgItemMessageW(h,10,CB_SETCURSEL,0,0);add(L"BUTTON",L"转为 SDR 显示(所有预览,立即生效)",12,BS_AUTOCHECKBOX|WS_TABSTOP);SendDlgItemMessageW(h,12,BM_SETCHECK,readSdr()?BST_CHECKED:BST_UNCHECKED,0);add(L"COMBOBOX",L"",13,CBS_DROPDOWNLIST|WS_VSCROLL|WS_TABSTOP);add(L"STATIC",L"采集音频(变更需重连)",14,0);- for(auto name:{L"自动:优先线性 PCM,必要时 Dolby/DTS 位流解码",L"强制线性 PCM(不接受 Dolby/DTS 位流)",L"位流优先:Dolby/DTS 直通并解码为 PCM"})SendDlgItemMessageW(h,13,CB_ADDSTRING,0,LPARAM(name));+ for(auto name:{L"自动:优先线性 PCM,必要时 Dolby/DTS 位流解码",L"强制线性 PCM(不接受 Dolby/DTS 位流)",L"位流优先:优先直通给功放(无直通时解码为 PCM)"})SendDlgItemMessageW(h,13,CB_ADDSTRING,0,LPARAM(name));SendDlgItemMessageW(h,13,CB_SETCURSEL,WPARAM(std::clamp(readAudioIngress?readAudioIngress():0,0,2)),0);add(L"BUTTON",L"连接并开始观看",4,BS_PUSHBUTTON|WS_TABSTOP);marked(GetDlgItem(h,4));add(L"BUTTON",L"刷新设备",5,BS_PUSHBUTTON|WS_TABSTOP);add(L"STATIC",L"视频输入设备",6,0);add(L"STATIC",L"设备实际支持的格式",7,0);add(L"STATIC",L"",8,0);add(L"STATIC",L"音频监听(仅采集所选输入,默认关闭)",9,0);- installDialogHelp(h,{{13,L"采集卡把 Dolby Atmos / Dolby Audio / DTS 以位流送来时,这里决定用哪条路。设备本身的音频格式不受影响;改这个要重新连接采集卡。自动优先 PCM,PCM 不可用时才走位流解码;位流优先则反过来,适合 PS5 已设成 Dolby 输出、但设备同时提供 PCM 的情况。"},{12,L"收到HDR也转成SDR显示,不用改PS5或Windows。增强照常用;只改预览,视频导出不受影响。切换会短暂停顿,截图跟随当前画面。关闭后跟随显示器。"},{10,L"设备没报HDR信息时手动指定,需选P010/P016。P010也可能装SDR,别给普通画面强戴HDR帽子。"},{1,L"选采集卡的视频设备。别把摄像头误请来直播PS5。"},{2,L"选设备真实提供的分辨率、帧率和像素格式。清晰度、带宽和延迟都受它影响。"},{3,L"如果设备自带 HDMI 音频,会显示“使用视频设备内置音频”;否则选择独立音频设备,也可不采声音。"},{4,L"按当前格式连接采集卡,并应用当前增强设置。"},{5,L"重新扫描设备和格式。设备被其他软件占用时,刷新不一定能抢回来。"}});+ installDialogHelp(h,{{13,L"采集卡把 Dolby Atmos / Dolby Audio / DTS 以位流送来时,这里决定用哪条路。设备本身的音频格式不受影响;改这个要重新连接采集卡。自动优先 PCM,PCM 不可用时才走位流解码;位流优先则反过来:先尝试把位流原样直通给功放/回音壁(独占输出,卡不经过软件解码,只有接收端才能解出 Atmos/DTS:X 的对象声场;需要输出设备支持,探测见日志 bitstream-out),没有支持的输出端点时自动回退到解码。适合 PS5 已设成 Dolby 输出、但设备同时提供 PCM 的情况。"},{12,L"收到HDR也转成SDR显示,不用改PS5或Windows。增强照常用;只改预览,视频导出不受影响。切换会短暂停顿,截图跟随当前画面。关闭后跟随显示器。"},{10,L"设备没报HDR信息时手动指定,需选P010/P016。P010也可能装SDR,别给普通画面强戴HDR帽子。"},{1,L"选采集卡的视频设备。别把摄像头误请来直播PS5。"},{2,L"选设备真实提供的分辨率、帧率和像素格式。清晰度、带宽和延迟都受它影响。"},{3,L"如果设备自带 HDMI 音频,会显示“使用视频设备内置音频”;否则选择独立音频设备,也可不采声音。"},{4,L"按当前格式连接采集卡,并应用当前增强设置。"},{5,L"重新扫描设备和格式。设备被其他软件占用时,刷新不一定能抢回来。"}});EnableWindow(GetDlgItem(h,4),FALSE);arrange();SetTimer(h,1,100,nullptr);if(!busy)query(-1);return 0;}case WM_TIMER:SendDlgItemMessageW(h,12,BM_SETCHECK,readSdr()?BST_CHECKED:BST_UNCHECKED,0);diff --git a/docs/WORKLOG.md b/docs/WORKLOG.mdindex cefc58e7..7af6f6c3 100644--- a/docs/WORKLOG.md+++ b/docs/WORKLOG.md@@ -50,7 +50,15 @@- **FSR→XeSS 实机边界(结论)**:FidelityFX 代理占用窗口唯一的 flip-model swapchain 槽位;**完整销毁**(官方顺序+排空+释放最后 COM 引用,refcount 实测归 2→0)后窗口仍无法承载任何新 swapchain——XeSS 创建、native 创建、甚至 FFX 自己重建代理全部失败(逐一实测)。因此改为:保留代理、拒绝切换、回滚到健康的 FSR 会话(无崩溃,FSR 继续生成:477 帧);恢复路径给 UI 提示"切到 XeSS 需要重启软件"。`xefgSwapChainD3D12InitFromSwapChain` 包装路径已实现,留作 FFX 行为变化后的入口。- 附带修复:`PresentSink` 重新初始化前 `swapChain_.Reset()`(`ComPtr::GetAddressOf` 直接写入会泄漏旧引用);测试脚本 `scripts/acceptance/ui-fsr-xess-switch.py`(PASS)。- 证据:delivery `logs/delivery/899266286a2f46cda5480bae0a3721bb/result.json`。-- **未完成(如实)**:杜比位流直通输出(独占 WASAPI+IEC 61937+端点能力探测)需要独立施工轮次;已完成的杜比相关项仍为 G-1 探测与 G-2 解码兜底。+- **(后续已补:见下节 2026-09-16 杜比位流直通)**++### 2026-09-16 杜比/DTS 位流直通输出(用户要求"杜比直通先做")++- **端点能力探测**(`tools/bitstream_audio_probe`,`veyra_bitstream_probe`):枚举渲染端点,在独占模式下对 AC-3 / E-AC-3(DD+,Atmos 载体) / DTS / TrueHD 逐一 `IsFormatSupported`。**本机实测**:Realtek Digital Output(SPDIF)**AC-3 与 DTS 均为 exact 支持**;模拟输出、虚拟声卡、NVIDIA HDMI(S2700)全部 `0x88890008`(不支持的格式)。**E-AC-3/TrueHD 全端点不支持**——Windows 端点上 DD+/Atmos 直通声明面窄是平台现实,探测如实报告。+- **`sink::BitstreamAudioSink`**(`include/veyra/sink/BitstreamAudioSink.h` / `src/sink/BitstreamAudioSink.cpp`):独占 WASAPI(16-bit 立体声 IEC 61937 载波、500ms 缓冲),自动选择第一个精确接受目标载波的活跃端点(可传入首选端点),按字节流转发压缩数据(IEC 61937 自同步,无需重打包),帧对齐由内部尾缓冲保证。自主实现,无第三方代码。+- **接线**(`CaptureCardSource`):在"位流优先"模式(`captureAudio=2`)且输入为 IEC 61937 封装时,**先尝试直通**(按 kind 选择 AC-3/DD+/TrueHD/DTS 载波,采样率取媒体类型);端点不支持或连接失败则**回退到现有的软件解码路径**(G-2),不改变自动/强制 PCM 模式的任何行为。直通会话不经过 `CaptureAudioSession`(位流无法调音量/无法软件同步,这是直通的固有语义);视频调度不依赖该会话(`videoPresented` 双路径判空,安全)。+- **验证**:`veyra_bitstream_probe 48000 --write-test` 在本机 SPDIF 上打开独占 AC-3 载波并写穿数据通路(`endpoint[1] wrote 245760 bytes through the exclusive carrier`);delivery 短测 PASS `logs/delivery/e09ea0d7fdb34e38b238ee12dd255fc5/result.json`。UI 文案与帮助同步更新("位流优先:优先直通给功放(无直通时解码为 PCM)")。+- **未验证(如实)**:本机采集卡不提供位流(G-1),**没有端到端的真实 Dolby 源验证**;需要持"支持位流输入的采集卡 + 支持解码的功放/回音壁"的用户按"位流优先"模式实测并回传 `capture-audio-bitstream` 日志(应出现 `passthrough to receiver kind=... endpoint="..."`)。E-AC-3/Atmos 直通依赖端点驱动声明,当前主流 Windows 端点普遍不支持。## 2026-09-15 采集卡直播窗口标题修复(第三方工具“识别不到 Veyra”)diff --git a/include/veyra/sink/BitstreamAudioSink.h b/include/veyra/sink/BitstreamAudioSink.hnew file mode 100644index 00000000..f85da2d3--- /dev/null+++ b/include/veyra/sink/BitstreamAudioSink.h@@ -0,0 +1,66 @@+#pragma once++// Dolby / DTS compressed-audio passthrough output.+//+// When the capture endpoint delivers an IEC 61937 compressed stream (Dolby+// Digital, Dolby Digital Plus, DTS, ...) the player can forward it unmodified+// to a receiver instead of decoding it. The receiver then performs the real+// decode, which is the only way a Dolby Atmos (E-AC-3 + JOC) or DTS:X stream+// keeps its object metadata - a PCM decode inside the player cannot.+//+// This sink owns a WASAPI *exclusive* stream on the first active render+// endpoint that advertises the matching IEC 61937 carrier format. Exclusive+// mode is required: the shared engine only accepts PCM. Compressed frames are+// written as a byte stream; IEC 61937 is self-synchronising, so no packet+// repacking is needed.++#include <windows.h>+#include <mmreg.h>++#include <cstdint>+#include <memory>+#include <string>++namespace veyra::sink {++struct BitstreamAudioSinkState {+ bool open = false;+ uint32_t sampleRate = 0;+ std::wstring endpointName;+ std::wstring endpointId;+ uint64_t bytesWritten = 0;+ uint64_t framesWritten = 0;+ uint64_t underruns = 0;+ std::wstring error;+};++class BitstreamAudioSink {+public:+ BitstreamAudioSink();+ ~BitstreamAudioSink();+ BitstreamAudioSink(const BitstreamAudioSink&) = delete;+ BitstreamAudioSink& operator=(const BitstreamAudioSink&) = delete;++ // Opens an exclusive WASAPI stream for `subtype` (one of the+ // KSDATAFORMAT_SUBTYPE_IEC61937_* GUIDs) at `sampleRate`, choosing the+ // first active render endpoint that accepts the format exactly.+ // `preferredEndpointId` (optional) is tried first, e.g. the endpoint the+ // PCM path already uses, so a device with both PCM and passthrough+ // support keeps one routing target.+ bool open(const GUID& subtype, uint32_t sampleRate,+ const std::wstring& preferredEndpointId = {});+ // Forwards one chunk of the compressed stream. Blocks briefly while the+ // endpoint buffer is full; byte counts that do not fill a 16-bit stereo+ // frame are held back for the next call.+ bool write(const uint8_t* data, size_t bytes);+ void close();++ bool opened() const;+ const BitstreamAudioSinkState& state() const;++private:+ struct Impl;+ std::unique_ptr<Impl> p_;+};++} // namespace veyra::sinkdiff --git a/src/sink/BitstreamAudioSink.cpp b/src/sink/BitstreamAudioSink.cppnew file mode 100644index 00000000..cb9e4e3c--- /dev/null+++ b/src/sink/BitstreamAudioSink.cpp@@ -0,0 +1,298 @@+#include "veyra/sink/BitstreamAudioSink.h"++#include "veyra/Log.h"++#include <initguid.h>+#include <ks.h>+#include <ksmedia.h>+#include <mmdeviceapi.h>+#include <audioclient.h>+#include <functiondiscoverykeys_devpkey.h>++#include <algorithm>+#include <cstring>+#include <format>+#include <thread>++namespace veyra::sink {+namespace {++std::wstring friendlyName(IMMDevice* device) {+ IPropertyStore* store = nullptr;+ std::wstring name = L"(unnamed)";+ if (SUCCEEDED(device->OpenPropertyStore(STGM_READ, &store)) && store != nullptr) {+ PROPVARIANT value{};+ if (SUCCEEDED(store->GetValue(PKEY_Device_FriendlyName, &value)) &&+ value.vt == VT_LPWSTR) {+ name = value.pwszVal;+ }+ PropVariantClear(&value);+ store->Release();+ }+ return name;+}++WAVEFORMATEXTENSIBLE carrierFormat(const GUID& subtype, uint32_t sampleRate) {+ WAVEFORMATEXTENSIBLE format{};+ format.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;+ format.Format.nChannels = 2;+ format.Format.nSamplesPerSec = sampleRate;+ format.Format.wBitsPerSample = 16;+ format.Format.nBlockAlign = 4;+ format.Format.nAvgBytesPerSec = sampleRate * 4;+ format.Format.cbSize = sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX);+ format.Samples.wValidBitsPerSample = 16;+ format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT;+ format.SubFormat = subtype;+ return format;+}++} // namespace++struct BitstreamAudioSink::Impl {+ IMMDeviceEnumerator* enumerator = nullptr;+ IMMDevice* device = nullptr;+ IAudioClient* client = nullptr;+ IAudioRenderClient* render = nullptr;+ uint32_t bufferFrames = 0;+ uint32_t frameBytes = 4; // 16-bit stereo carrier+ uint8_t tail[8]{};+ size_t tailBytes = 0;+ bool comInitialized = false;+ BitstreamAudioSinkState state{};++ ~Impl() { shutdown(); }++ void shutdown() {+ if (client != nullptr) {+ client->Stop();+ }+ if (render != nullptr) {+ render->Release();+ render = nullptr;+ }+ if (client != nullptr) {+ client->Release();+ client = nullptr;+ }+ if (device != nullptr) {+ device->Release();+ device = nullptr;+ }+ if (enumerator != nullptr) {+ enumerator->Release();+ enumerator = nullptr;+ }+ state.open = false;+ }++ bool tryEndpoint(IMMDevice* candidate, const WAVEFORMATEXTENSIBLE& format) {+ IAudioClient* audio = nullptr;+ if (FAILED(candidate->Activate(__uuidof(IAudioClient), CLSCTX_ALL, nullptr,+ reinterpret_cast<void**>(&audio))) ||+ audio == nullptr) {+ return false;+ }+ WAVEFORMATEX* closest = nullptr;+ const HRESULT support = audio->IsFormatSupported(+ AUDCLNT_SHAREMODE_EXCLUSIVE,+ reinterpret_cast<const WAVEFORMATEX*>(&format), &closest);+ if (closest != nullptr) CoTaskMemFree(closest);+ if (support != S_OK) {+ audio->Release();+ return false;+ }+ // 500 ms of carrier keeps the exclusive stream tolerant of small+ // scheduling jitter without adding meaningful latency.+ const HRESULT init = audio->Initialize(AUDCLNT_SHAREMODE_EXCLUSIVE, 0,+ 5000000, 0,+ reinterpret_cast<const WAVEFORMATEX*>(&format),+ nullptr);+ if (FAILED(init)) {+ audio->Release();+ return false;+ }+ IAudioRenderClient* renderClient = nullptr;+ if (FAILED(audio->GetService(__uuidof(IAudioRenderClient),+ reinterpret_cast<void**>(&renderClient))) ||+ renderClient == nullptr) {+ audio->Release();+ return false;+ }+ UINT32 frames = 0;+ audio->GetBufferSize(&frames);+ if (FAILED(audio->Start()) || frames == 0) {+ renderClient->Release();+ audio->Release();+ return false;+ }+ client = audio;+ render = renderClient;+ device = candidate;+ device->AddRef();+ bufferFrames = frames;+ return true;+ }+};++BitstreamAudioSink::BitstreamAudioSink() : p_(std::make_unique<Impl>()) {}+BitstreamAudioSink::~BitstreamAudioSink() { close(); }++bool BitstreamAudioSink::open(const GUID& subtype, uint32_t sampleRate,+ const std::wstring& preferredEndpointId) {+ auto& p = *p_;+ if (p.state.open) return true;+ if (sampleRate == 0) sampleRate = 48000;+ const WAVEFORMATEXTENSIBLE format = carrierFormat(subtype, sampleRate);++ const HRESULT comHr = CoInitializeEx(nullptr, COINIT_MULTITHREADED);+ if (SUCCEEDED(comHr)) {+ p.comInitialized = true;+ } else if (comHr != RPC_E_CHANGED_MODE) {+ p.state.error = L"COM initialization failed";+ return false;+ }+ HRESULT hr = CoCreateInstance(__uuidof(MMDeviceEnumerator), nullptr, CLSCTX_ALL,+ __uuidof(IMMDeviceEnumerator),+ reinterpret_cast<void**>(&p.enumerator));+ if (FAILED(hr) || p.enumerator == nullptr) {+ p.state.error = L"audio device enumerator unavailable";+ return false;+ }+ IMMDeviceCollection* collection = nullptr;+ hr = p.enumerator->EnumAudioEndpoints(eRender, DEVICE_STATE_ACTIVE, &collection);+ if (FAILED(hr) || collection == nullptr) {+ p.state.error = L"render endpoint enumeration failed";+ return false;+ }+ UINT count = 0;+ collection->GetCount(&count);++ // Preferred endpoint first (usually the one the PCM path uses), then any+ // other endpoint that advertises the carrier format exactly.+ bool opened = false;+ if (!preferredEndpointId.empty()) {+ for (UINT index = 0; index < count && !opened; ++index) {+ IMMDevice* candidate = nullptr;+ if (FAILED(collection->Item(index, &candidate)) || candidate == nullptr) continue;+ LPWSTR id = nullptr;+ bool matches = SUCCEEDED(candidate->GetId(&id)) && id != nullptr &&+ preferredEndpointId == id;+ if (id != nullptr) CoTaskMemFree(id);+ if (matches) {+ opened = p.tryEndpoint(candidate, format);+ if (opened) {+ p.state.endpointName = friendlyName(candidate);+ }+ }+ if (!opened) candidate->Release();+ }+ }+ for (UINT index = 0; index < count && !opened; ++index) {+ IMMDevice* candidate = nullptr;+ if (FAILED(collection->Item(index, &candidate)) || candidate == nullptr) continue;+ opened = p.tryEndpoint(candidate, format);+ if (opened) {+ p.state.endpointName = friendlyName(candidate);+ } else {+ candidate->Release();+ }+ }+ if (opened) {+ LPWSTR id = nullptr;+ if (SUCCEEDED(p.device->GetId(&id)) && id != nullptr) {+ p.state.endpointId = id;+ CoTaskMemFree(id);+ }+ }+ collection->Release();+ if (!opened) {+ p.state.error = L"no active render endpoint accepts the IEC 61937 carrier";+ log::warn("bitstream-out", "no render endpoint accepted the compressed carrier format");+ return false;+ }+ p.state.open = true;+ p.state.sampleRate = sampleRate;+ log::info("bitstream-out", std::format(+ "passthrough stream open endpoint=\"{}\" rate={}Hz 16-bit stereo carrier",+ std::string(p.state.endpointName.begin(), p.state.endpointName.end()), sampleRate));+ return true;+}++bool BitstreamAudioSink::write(const uint8_t* data, size_t bytes) {+ auto& p = *p_;+ if (!p.state.open || p.client == nullptr || p.render == nullptr) return false;+ if (data == nullptr || bytes == 0) return true;++ // Keep frame alignment: hold back a trailing partial carrier frame.+ size_t consumed = 0;+ if (p.tailBytes != 0) {+ const size_t need = p.frameBytes - p.tailBytes;+ const size_t take = std::min(need, bytes);+ std::memcpy(p.tail + p.tailBytes, data, take);+ p.tailBytes += take;+ consumed += take;+ if (p.tailBytes < p.frameBytes) return true;+ // Fall through: the completed tail frame is written below.+ }+ const uint8_t* cursor = data + consumed;+ size_t remaining = bytes - consumed;+ auto writeBlock = [&](const uint8_t* block, size_t blockBytes) -> bool {+ size_t offset = 0;+ while (offset < blockBytes) {+ const uint32_t frames = static_cast<uint32_t>((blockBytes - offset) / p.frameBytes);+ if (frames == 0) return true;+ UINT32 padding = 0;+ if (FAILED(p.client->GetCurrentPadding(&padding))) return false;+ const uint32_t available = padding < p.bufferFrames ? p.bufferFrames - padding : 0;+ if (available == 0) {+ ++p.state.underruns;+ std::this_thread::sleep_for(std::chrono::milliseconds(2));+ continue;+ }+ const uint32_t chunk = std::min(frames, available);+ BYTE* destination = nullptr;+ if (FAILED(p.render->GetBuffer(chunk, &destination)) || destination == nullptr) {+ return false;+ }+ std::memcpy(destination, block + offset, size_t(chunk) * p.frameBytes);+ p.render->ReleaseBuffer(chunk, 0);+ offset += size_t(chunk) * p.frameBytes;+ p.state.framesWritten += chunk;+ p.state.bytesWritten += size_t(chunk) * p.frameBytes;+ }+ return true;+ };+ if (p.tailBytes == p.frameBytes) {+ if (!writeBlock(p.tail, p.frameBytes)) return false;+ p.tailBytes = 0;+ }+ const size_t whole = remaining - (remaining % p.frameBytes);+ if (whole != 0 && !writeBlock(cursor, whole)) return false;+ if (remaining > whole) {+ std::memcpy(p.tail, cursor + whole, remaining - whole);+ p.tailBytes = remaining - whole;+ }+ return true;+}++void BitstreamAudioSink::close() {+ auto& p = *p_;+ if (p.state.open) {+ log::info("bitstream-out", std::format(+ "passthrough stream closed endpoint=\"{}\" bytes={} frames={} stalls={}",+ std::string(p.state.endpointName.begin(), p.state.endpointName.end()),+ p.state.bytesWritten, p.state.framesWritten, p.state.underruns));+ }+ p.shutdown();+ if (p.comInitialized) {+ CoUninitialize();+ p.comInitialized = false;+ }+}++bool BitstreamAudioSink::opened() const { return p_->state.open; }++const BitstreamAudioSinkState& BitstreamAudioSink::state() const { return p_->state; }++} // namespace veyra::sinkdiff --git a/src/source/CaptureCardSource.cpp b/src/source/CaptureCardSource.cppindex e2c2cf1a..ccbc75b6 100644--- a/src/source/CaptureCardSource.cpp+++ b/src/source/CaptureCardSource.cpp@@ -7,9 +7,12 @@#include "veyra/Log.h"#include "veyra/sink/AudioFormat.h"#include "veyra/sink/BitstreamAudio.h"+#include "veyra/sink/BitstreamAudioSink.h"#include <windows.h>#include <dshow.h>#include <dvdmedia.h>+#include <ks.h>+#include <ksmedia.h>#include <wrl/client.h>#include <algorithm>#include <array>@@ -130,6 +133,9 @@ struct CaptureCardSource::Impl:ISampleGrabberCB {// the raw bursts are decoded here and the session is configured with the// decoded layout on the first frame (that is why its start is deferred).std::shared_ptr<sink::BitstreamDecoder> audioBitstream;+ // Bitstream-first mode: the compressed stream is forwarded unmodified to a+ // receiver over an exclusive WASAPI IEC 61937 carrier when one accepts it.+ std::shared_ptr<sink::BitstreamAudioSink> audioPassthrough;bool audioSessionDeferred=false;std::wstring audioBitstreamKind;// 0 automatic, 1 PCM only, 2 bitstream preferred (see@@ -437,6 +443,55 @@ if(audioTypes.empty()&&(!allowBitstream||bitstreamTypes.empty())){log::warn("capauto* type=owned.get();const auto kind=sink::classifyBitstreamSubtype(type->subtype.Data1);const bool iec=sink::bitstreamIsIec61937(type->subtype.Data1);+ // Bitstream-first mode with an IEC 61937 framed input: forward the+ // compressed stream unchanged to a receiver that accepts the+ // matching carrier (exclusive WASAPI). Only the receiver can+ // decode Dolby Atmos / DTS:X object audio; the in-player decode+ // below would reduce it to plain 5.1 PCM. Falls back silently when+ // no endpoint advertises the format.+ if(wantBitstreamFirst&&iec){+ const GUID* carrier=nullptr;+ switch(kind){+ case sink::BitstreamKind::Ac3:carrier=&KSDATAFORMAT_SUBTYPE_IEC61937_DOLBY_DIGITAL;break;+ case sink::BitstreamKind::Eac3:carrier=&KSDATAFORMAT_SUBTYPE_IEC61937_DOLBY_DIGITAL_PLUS;break;+ case sink::BitstreamKind::TrueHd:carrier=&KSDATAFORMAT_SUBTYPE_IEC61937_DOLBY_MLP;break;+ case sink::BitstreamKind::Dts:carrier=&KSDATAFORMAT_SUBTYPE_IEC61937_DTS;break;+ // DTS-HD has no standard IEC 61937 subtype on Windows; it+ // stays on the decode path.+ default:break;+ }+ uint32_t rate=48000;+ if(type->pbFormat!=nullptr&&type->cbFormat>=sizeof(WAVEFORMATEX)){+ const auto* wave=reinterpret_cast<const WAVEFORMATEX*>(type->pbFormat);+ if(wave->nSamplesPerSec==44100||wave->nSamplesPerSec==48000||wave->nSamplesPerSec==96000||wave->nSamplesPerSec==192000)rate=wave->nSamplesPerSec;+ }+ if(carrier!=nullptr){+ auto passthrough=std::make_shared<sink::BitstreamAudioSink>();+ if(passthrough->open(*carrier,rate)){+ ComPtr<IBaseFilter> candidate;ComPtr<IPin> terminal;+ auto sink=passthrough;+ hr=createNativeAudioSink(*type,[sink](IMediaSample* sample){+ BYTE* bytes=nullptr;+ if(FAILED(sample->GetPointer(&bytes)))return VFW_E_SAMPLE_TIME_NOT_SET;+ return sink->write(bytes,size_t(sample->GetActualDataLength()))?S_OK:E_FAIL;+ },candidate,terminal);+ if(SUCCEEDED(hr))hr=p.graph->AddFilter(candidate.Get(),L"Veyra audio bitstream passthrough");+ if(SUCCEEDED(hr))hr=p.graph->ConnectDirect(audioPin.Get(),terminal.Get(),type);+ if(SUCCEEDED(hr)){+ p.audioSink=candidate;p.audioPassthrough=passthrough;+ {const std::string name=sink::bitstreamKindName(kind);p.audioBitstreamKind.assign(name.begin(),name.end());}+ const auto& sinkState=passthrough->state();+ log::info("capture-audio-bitstream",std::string("passthrough to receiver kind=")+sink::bitstreamKindName(kind)++ std::format(" rate={} endpoint=\"{}\" (no in-player decode)",rate,+ std::string(sinkState.endpointName.begin(),sinkState.endpointName.end())));+ connectedAudio=true;+ }else if(candidate)p.graph->RemoveFilter(candidate.Get());+ }else{+ log::info("capture-audio-bitstream",std::string("receiver passthrough unavailable for ")+sink::bitstreamKindName(kind)+"; decoding to PCM");+ }+ if(connectedAudio)break;+ }+ }auto decoder=std::make_shared<sink::BitstreamDecoder>();if(!decoder->open(kind,iec)){log::warn("capture-audio-bitstream",std::string("decoder unavailable for ")+sink::bitstreamKindName(kind)+": "+decoder->lastError());@@ -586,7 +641,8 @@ void CaptureCardSource::close()noexcept{auto& p=*p_;if(p.control){const HRESULT hr=p.control->Stop();if(FAILED(hr))log::error("capture-close",std::format("Stop failed hr=0x{:08X}; releasing graph",uint32_t(hr)));}if(p.grab){const HRESULT hr=p.grab->SetCallback(nullptr,0);if(FAILED(hr))log::error("capture-close",std::format("detach callback hr=0x{:08X}",uint32_t(hr)));}if(p.wasapi)p.wasapi->stop();p.wasapi.reset();if(p.audioSession)p.audioSession->stop();p.audioError.clear();- p.events.Reset();p.control.Reset();p.grab.Reset();p.nullFilter.Reset();p.grabFilter.Reset();p.audioSink.Reset();p.audioFilter.Reset();p.config.Reset();p.device.Reset();p.builder.Reset();p.graph.Reset();p.referenceClock.Reset();p.audioSession.reset();+ if(p.audioPassthrough)p.audioPassthrough->close();+ p.events.Reset();p.control.Reset();p.grab.Reset();p.nullFilter.Reset();p.grabFilter.Reset();p.audioSink.Reset();p.audioFilter.Reset();p.config.Reset();p.device.Reset();p.builder.Reset();p.graph.Reset();p.referenceClock.Reset();p.audioSession.reset();p.audioPassthrough.reset();av_frame_free(&p.frame);av_frame_free(&p.pendingFrame);p.info={};p.sequence=p.received=p.dropped=p.lastDrop=0;p.pending=p.callbackError=p.configured=p.forceDiscontinuity=false;p.lastPts=p.readAgeMs=0;}diff --git a/tools/bitstream_audio_probe/main.cpp b/tools/bitstream_audio_probe/main.cppnew file mode 100644index 00000000..3acd6719--- /dev/null+++ b/tools/bitstream_audio_probe/main.cpp@@ -0,0 +1,244 @@+// Dolby / DTS endpoint passthrough probe (diagnostic only, never shipped).+//+// Enumerates render endpoints and asks each one, in WASAPI exclusive mode,+// whether it accepts the IEC 61937 carrier formats used for compressed+// passthrough (AC-3, E-AC-3/DD+, DTS, TrueHD). A receiver behind HDMI/SPDIF+// only gets real Atmos/DTS:X when the endpoint advertises these formats; the+// player can then forward the capture bitstream without decoding.+//+// Usage: veyra_bitstream_probe [sampleRate] [--write-test]+#include <windows.h>+#include <initguid.h>+#include <ks.h>+#include <ksmedia.h>+#include <mmdeviceapi.h>+#include <audioclient.h>+#include <functiondiscoverykeys_devpkey.h>++#include <cstdio>+#include <cstring>+#include <string>+#include <vector>++namespace {++std::string toUtf8(const wchar_t* value) {+ if (value == nullptr) return {};+ const int length = WideCharToMultiByte(CP_UTF8, 0, value, -1, nullptr, 0, nullptr, nullptr);+ std::string text(size_t(length > 0 ? length - 1 : 0), '\0');+ if (length > 1) WideCharToMultiByte(CP_UTF8, 0, value, -1, text.data(), length, nullptr, nullptr);+ return text;+}++WAVEFORMATEXTENSIBLE iec61937Format(const GUID& subtype, uint32_t sampleRate) {+ WAVEFORMATEXTENSIBLE format{};+ format.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;+ format.Format.nChannels = 2;+ format.Format.nSamplesPerSec = sampleRate;+ format.Format.wBitsPerSample = 16;+ format.Format.nBlockAlign = 4;+ format.Format.nAvgBytesPerSec = sampleRate * 4;+ format.Format.cbSize = sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX);+ format.Samples.wValidBitsPerSample = 16;+ format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT;+ format.SubFormat = subtype;+ return format;+}++struct FormatCase {+ const char* name;+ const GUID* subtype;+};++std::string describeHr(HRESULT hr) {+ char buffer[32]{};+ std::snprintf(buffer, sizeof(buffer), "0x%08X", static_cast<unsigned>(hr));+ return buffer;+}++} // namespace++int wmain(int argc, wchar_t** argv) {+ setvbuf(stdout, nullptr, _IONBF, 0);+ uint32_t sampleRate = 48000;+ bool writeTest = false;+ for (int i = 1; i < argc; ++i) {+ if (_wcsicmp(argv[i], L"--write-test") == 0) writeTest = true;+ }+ if (argc > 1 && _wtoi(argv[1]) > 0) {+ const int requested = _wtoi(argv[1]);+ if (requested == 44100 || requested == 48000 || requested == 96000 ||+ requested == 192000) {+ sampleRate = static_cast<uint32_t>(requested);+ }+ }+ const FormatCase cases[] = {+ {"AC-3 (Dolby Digital)", &KSDATAFORMAT_SUBTYPE_IEC61937_DOLBY_DIGITAL},+ {"E-AC-3 (Dolby Digital Plus / Atmos carrier)",+ &KSDATAFORMAT_SUBTYPE_IEC61937_DOLBY_DIGITAL_PLUS},+ {"DTS", &KSDATAFORMAT_SUBTYPE_IEC61937_DTS},+ {"Dolby TrueHD / MLP", &KSDATAFORMAT_SUBTYPE_IEC61937_DOLBY_MLP},+ };++ const HRESULT comHr = CoInitializeEx(nullptr, COINIT_MULTITHREADED);+ if (FAILED(comHr)) {+ std::printf("[bitstream] CoInitializeEx failed %s\n", describeHr(comHr).c_str());+ return 2;+ }+ IMMDeviceEnumerator* enumerator = nullptr;+ HRESULT hr = CoCreateInstance(__uuidof(MMDeviceEnumerator), nullptr, CLSCTX_ALL,+ __uuidof(IMMDeviceEnumerator),+ reinterpret_cast<void**>(&enumerator));+ if (FAILED(hr)) {+ std::printf("[bitstream] device enumerator failed %s\n", describeHr(hr).c_str());+ return 3;+ }+ IMMDeviceCollection* collection = nullptr;+ hr = enumerator->EnumAudioEndpoints(eRender, DEVICE_STATE_ACTIVE, &collection);+ if (FAILED(hr)) {+ std::printf("[bitstream] endpoint enumeration failed %s\n", describeHr(hr).c_str());+ enumerator->Release();+ return 3;+ }+ UINT count = 0;+ collection->GetCount(&count);+ std::printf("[bitstream] render endpoints=%u sampleRate=%u\n", count, sampleRate);+ for (UINT index = 0; index < count; ++index) {+ IMMDevice* device = nullptr;+ if (FAILED(collection->Item(index, &device)) || device == nullptr) continue;+ IPropertyStore* store = nullptr;+ std::string name = "(unnamed)";+ std::string deviceId = "(no id)";+ if (SUCCEEDED(device->OpenPropertyStore(STGM_READ, &store)) && store != nullptr) {+ PROPVARIANT value{};+ if (SUCCEEDED(store->GetValue(PKEY_Device_FriendlyName, &value)) &&+ value.vt == VT_LPWSTR) {+ name = toUtf8(value.pwszVal);+ }+ PropVariantClear(&value);+ store->Release();+ }+ {+ LPWSTR id = nullptr;+ if (SUCCEEDED(device->GetId(&id)) && id != nullptr) {+ deviceId = toUtf8(id);+ CoTaskMemFree(id);+ }+ }+ IAudioClient* client = nullptr;+ hr = device->Activate(__uuidof(IAudioClient), CLSCTX_ALL, nullptr,+ reinterpret_cast<void**>(&client));+ std::printf("\n[%u] %s\n id=%s\n activate=%s\n", index, name.c_str(),+ deviceId.c_str(), describeHr(hr).c_str());+ if (SUCCEEDED(hr) && client != nullptr) {+ for (const auto& entry : cases) {+ WAVEFORMATEXTENSIBLE format = iec61937Format(*entry.subtype, sampleRate);+ WAVEFORMATEX* closest = nullptr;+ const HRESULT support = client->IsFormatSupported(+ AUDCLNT_SHAREMODE_EXCLUSIVE,+ reinterpret_cast<const WAVEFORMATEX*>(&format), &closest);+ if (closest != nullptr) CoTaskMemFree(closest);+ const char* verdict = "no";+ if (support == S_OK) verdict = "YES (exact)";+ else if (support == S_FALSE) verdict = "near (resampled/other rate)";+ std::printf(" %-45s %s %s\n", entry.name, verdict,+ describeHr(support).c_str());+ }+ client->Release();+ }+ device->Release();+ }+ collection->Release();+ enumerator->Release();++ if (writeTest) {+ // Open an exclusive AC-3 carrier on the first endpoint that supports+ // it and write synthetic bursts through the same code path the+ // passthrough sink uses. The receiver, when one is attached, decides+ // whether the silent pattern is decodable; the probe only proves the+ // stream opens and accepts data.+ std::printf("\n[write-test] opening exclusive AC-3 carrier @ %u Hz\n", sampleRate);+ IMMDeviceEnumerator* enum2 = nullptr;+ if (SUCCEEDED(CoCreateInstance(__uuidof(MMDeviceEnumerator), nullptr, CLSCTX_ALL,+ __uuidof(IMMDeviceEnumerator),+ reinterpret_cast<void**>(&enum2))) && enum2 != nullptr) {+ IMMDeviceCollection* render = nullptr;+ if (SUCCEEDED(enum2->EnumAudioEndpoints(eRender, DEVICE_STATE_ACTIVE, &render)) &&+ render != nullptr) {+ UINT total = 0;+ render->GetCount(&total);+ for (UINT index = 0; index < total; ++index) {+ IMMDevice* candidate = nullptr;+ if (FAILED(render->Item(index, &candidate)) || candidate == nullptr) continue;+ IAudioClient* client = nullptr;+ if (SUCCEEDED(candidate->Activate(__uuidof(IAudioClient), CLSCTX_ALL, nullptr,+ reinterpret_cast<void**>(&client))) &&+ client != nullptr) {+ WAVEFORMATEXTENSIBLE format = iec61937Format(+ KSDATAFORMAT_SUBTYPE_IEC61937_DOLBY_DIGITAL, sampleRate);+ WAVEFORMATEX* closest = nullptr;+ const HRESULT support = client->IsFormatSupported(+ AUDCLNT_SHAREMODE_EXCLUSIVE,+ reinterpret_cast<const WAVEFORMATEX*>(&format), &closest);+ if (closest != nullptr) CoTaskMemFree(closest);+ if (support == S_OK &&+ SUCCEEDED(client->Initialize(AUDCLNT_SHAREMODE_EXCLUSIVE, 0, 5000000, 0,+ reinterpret_cast<const WAVEFORMATEX*>(&format),+ nullptr))) {+ IAudioRenderClient* renderClient = nullptr;+ UINT32 frames = 0;+ client->GetBufferSize(&frames);+ if (SUCCEEDED(client->GetService(__uuidof(IAudioRenderClient),+ reinterpret_cast<void**>(&renderClient))) &&+ renderClient != nullptr && frames != 0 &&+ SUCCEEDED(client->Start())) {+ std::vector<uint8_t> burst(6144, 0);+ // One IEC 61937 style burst header so the stream+ // is byte-aligned; content is silence.+ burst[0] = 0x72; burst[1] = 0xF8; burst[2] = 0x1F; burst[3] = 0x4E;+ uint64_t written = 0;+ for (int repeat = 0; repeat < 40; ++repeat) {+ UINT32 padding = 0;+ while (SUCCEEDED(client->GetCurrentPadding(&padding)) &&+ padding >= frames) {+ Sleep(2);+ }+ const UINT32 available = frames - padding;+ const UINT32 chunkFrames = available < burst.size() / 4+ ? available+ : static_cast<UINT32>(burst.size() / 4);+ if (chunkFrames == 0) break;+ BYTE* destination = nullptr;+ if (FAILED(renderClient->GetBuffer(chunkFrames, &destination)) ||+ destination == nullptr) {+ break;+ }+ std::memcpy(destination, burst.data(),+ std::min<size_t>(burst.size(),+ size_t(chunkFrames) * 4));+ renderClient->ReleaseBuffer(chunkFrames, 0);+ written += size_t(chunkFrames) * 4;+ Sleep(20);+ }+ client->Stop();+ std::printf("[write-test] endpoint[%u] wrote %llu bytes through the exclusive carrier\n",+ index, static_cast<unsigned long long>(written));+ renderClient->Release();+ }+ client->Release();+ candidate->Release();+ break;+ }+ client->Release();+ }+ candidate->Release();+ }+ render->Release();+ }+ enum2->Release();+ }+ }+ CoUninitialize();+ std::printf("\n[bitstream] probe complete (S_OK = endpoint accepts the IEC 61937 carrier)\n");+ return 0;+}