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): decode Dolby/DTS capture bitstreams back to PCM (G-2)
Veyra Goal Agent56bb0f6b918c
diff --git a/CMakeLists.txt b/CMakeLists.txtindex 48ab9d5b..37d83439 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -414,6 +414,7 @@ if(VEYRA_FFMPEG_ROOT AND EXISTS "${VEYRA_FFMPEG_ROOT}/include/libavformat/avformsrc/sink/WasapiAudioSink.cppsrc/sink/CaptureAudioSession.cppsrc/sink/CaptureAudioDsp.cpp+ src/sink/BitstreamAudio.cppsrc/sink/ImageExportSink.cppsrc/sink/NvencD3D12Encoder.cpp)@@ -427,8 +428,11 @@ if(VEYRA_FFMPEG_ROOT AND EXISTS "${VEYRA_FFMPEG_ROOT}/include/libavformat/avformtarget_include_directories(veyra_sinks PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/third_party_local/nvidia/nv-codec-headers/include")target_compile_definitions(veyra_sinks PRIVATE VEYRA_SHADER_DIR="${CMAKE_BINARY_DIR}/shaders")add_dependencies(veyra_sinks veyra_shader_rgb_nv12)- target_link_libraries(veyra_sinks PUBLIC veyra_base veyra_gfx ole32 windowscodecs mmdevapi avrt)+target_link_libraries(veyra_sinks PUBLIC veyra_base veyra_gfx ole32 windowscodecs mmdevapi avrt)target_link_libraries(veyra_sinks PRIVATE ${FFMPEG_LIBRARIES})+ if(FFMPEG_INCLUDE_DIRS)+ target_include_directories(veyra_sinks PRIVATE ${FFMPEG_INCLUDE_DIRS})+ endif()# veyra_sources: product input sources (Playbook R3/R7). MediaFileSource# composes veyra_media; no second decode implementation exists.@@ -521,6 +525,14 @@ if(VEYRA_FFMPEG_ROOT AND EXISTS "${VEYRA_FFMPEG_ROOT}/include/libavformat/avformtarget_compile_features(veyra_audio_timeline_tests PRIVATE cxx_std_20)target_link_libraries(veyra_audio_timeline_tests PRIVATE veyra_sinks)add_executable(veyra_capture_audio_tests tests/integration/CaptureAudioTests.cpp)+ if(VEYRA_FFMPEG_ROOT AND EXISTS "${VEYRA_FFMPEG_ROOT}/include/libavcodec/avcodec.h")+ add_executable(veyra_bitstream_audio_test tools/bitstream_audio_test/main.cpp)+ target_compile_features(veyra_bitstream_audio_test PRIVATE cxx_std_20)+ target_compile_options(veyra_bitstream_audio_test PRIVATE /utf-8 /WX-)+ target_compile_definitions(veyra_bitstream_audio_test PRIVATE NOMINMAX WIN32_LEAN_AND_MEAN UNICODE _UNICODE)+ target_include_directories(veyra_bitstream_audio_test PRIVATE ${FFMPEG_INCLUDE_DIRS})+ target_link_libraries(veyra_bitstream_audio_test PRIVATE veyra_sinks veyra_base ${FFMPEG_LIBRARIES})+ endif()add_executable(veyra_audio_waveform_tests tests/integration/AudioWaveformTests.cpp)target_compile_features(veyra_audio_waveform_tests PRIVATE cxx_std_20)target_compile_definitions(veyra_audio_waveform_tests PRIVATE NOMINMAX WIN32_LEAN_AND_MEAN)diff --git a/apps/veyra/ui/LiveStatusPanel.h b/apps/veyra/ui/LiveStatusPanel.hindex fda17ff3..9f569100 100644--- a/apps/veyra/ui/LiveStatusPanel.h+++ b/apps/veyra/ui/LiveStatusPanel.h@@ -137,7 +137,7 @@ inline LRESULT CALLBACK proc(HWND h,UINT message,WPARAM wp,LPARAM lp){}if(!s.capture&&s.audioAvailable)rows.emplace_back(L"声音领先 · 软件估算",std::format(L"{:.1f} ms",s.lateMs));if(s.capture&&s.audioAvailable){- rows.emplace_back(L"音频格式",std::format(L"{} Hz · {} bit / {} valid{}",s.captureAudio.inputSampleRate,s.captureAudio.inputContainerBits,s.captureAudio.inputValidBits,s.captureAudio.inputFloating?L" · Float":L""));+ rows.emplace_back(L"音频格式",std::format(L"{} Hz · {} bit / {} valid{}{}",s.captureAudio.inputSampleRate,s.captureAudio.inputContainerBits,s.captureAudio.inputValidBits,s.captureAudio.inputFloating?L" · Float":L"",s.captureAudio.inputBitstream.empty()?L"":std::format(L" · 位流解码为 {} 声道 ({})",s.captureAudio.inputChannels,s.captureAudio.inputBitstream)));rows.emplace_back(s.captureAudio.syncClockFallback?L"估算偏差 · 本机时钟":L"音画偏差 · 声音领先",ms(s.captureAudio.skewMs));rows.emplace_back(L"声音补偿",std::format(L"{:.1f} ms{}",s.captureAudio.compensationMs,s.captureAudio.limited?L" · 已达边界":L""));if(s.captureAudio.syncClockFallback)rows.emplace_back(L"同步状态",L"时间戳异常回退 · 本机延迟估算");diff --git a/docs/WORKLOG.md b/docs/WORKLOG.mdindex e5c521f9..03451bad 100644--- a/docs/WORKLOG.md+++ b/docs/WORKLOG.md@@ -2345,6 +2345,30 @@ DLSSG 能力门控没有排除 FSR,导致 FSR 会话下任何就地设置变### 2026-09-16 40 系 DLSS MFG 解锁(C-2)实现 + 本机结构/补丁机制验证+### 2026-09-16 杜比/DTS 位流解码兜底(G-2)实现 + 本地解码验证++新增 `include/veyra/sink/BitstreamAudio.h` + `src/sink/BitstreamAudio.cpp`(FFmpeg libavcodec/libswresample):+按 KSDATAFORMAT/WAVE subtype 分类 AC-3 / E-AC-3(含 DD+ Atmos 载体) / TrueHD-MLP / DTS / DTS-HD/DTS:X,+S/PDIF 的 IEC 61937 突发自动解框,解码为交错 float PCM 并给出真实声道数与采样率。++采集接线(`CaptureCardSource::configureAudio`):PCM 媒体类型仍然优先;当**没有任何 PCM 能连接**时,+按 TrueHD > DD+ > DTS-HD > DTS > AC-3 的优先级选压缩类型直通,首帧解码后用它报的声道数/采样率+配置并启动 `CaptureAudioSession`(`audioSessionDeferred`),随后按原有 `push()` 契约进入既有 5.1 管线;+状态面板新增"位流解码为 N 声道 (kind)"一行。本机参考采集卡没有位流类型(`device bitstream types=0`),+因此该分支不会被触发,PCM 路径实测不变:`capture:0:0:0` 425 帧 60fps、exit 0(`logs/fsr/capture-after-g2.log`)。++**本地可验证的部分已实测**:`veyra_bitstream_audio_test` 用同一份 FFmpeg 编码 2 秒 5.1 测试信号+(每声道不同幅度、LFE 用 60Hz 低音),再经 `BitstreamDecoder` 分块解码:++- AC-3 448kbps:6 声道、95232 帧,逐声道 RMS `0.3531/0.2824/0.2118/0.1765/0.1412/0.0706`+ → 与编码幅度(0.5/0.4/0.3/0.25/0.2/0.1 的正弦 RMS)逐项吻合,**声道映射与幅度都正确**;+- 同一份 AC-3 再套 IEC 61937 突发头:结果逐位一致 → 解框正确;+- E-AC-3 640kbps:同样 6 声道与同样的幅度序列。++**未验证**:真实采集卡的位流协商与长时稳定性(本机设备不提供位流);TrueHD/DTS-HD 只验证了解码器存在+(`avcodec_find_decoder` 命中)而没有真实素材,不得对外宣称已支持这两种格式的实机采集。+证据:`logs/fsr/bitstream-decode-test.log`;delivery 短测 PASS(`logs/delivery/622908bcc14b47a381340e8662c5b0a2/result.json`)。+移植 `ImDreamt/MFGAdaUnlock-RenoDx`(MIT,`third_party_local/community/`)到产品库`include/veyra/ngx/AdaMfgUnlock.h` + `src/ngx/AdaMfgUnlock.cpp`:两处 `0x1b0`(Blackwell) 架构比较改写为 `0x190`(Ada)、PTX 中点修正(注入 temporal 参数 + 104 处 `mul.ftz.f32 ...,0f3F000000`diff --git a/include/veyra/sink/BitstreamAudio.h b/include/veyra/sink/BitstreamAudio.hnew file mode 100644index 00000000..d68069e4--- /dev/null+++ b/include/veyra/sink/BitstreamAudio.h@@ -0,0 +1,67 @@+#pragma once++// Dolby / DTS bitstream support for the capture path.+//+// A capture card that is fed Dolby Atmos / Dolby Audio / DTS by the console+// exposes the audio pin as a *compressed* media type instead of PCM. Veyra used+// to enumerate those types and ignore them, so the user only ever got linear+// PCM. This module decodes such a stream back to interleaved float PCM so it can+// enter the existing 5.1 pipeline, and it also carries the (read-only)+// classification used to report device capability.+//+// Decoding uses the FFmpeg already shipped with the player (libavcodec ++// libswresample). Nothing here changes the PCM path: it is only selected when+// the device offers no usable PCM layout or when passthrough is requested.++#include <cstdint>+#include <memory>+#include <string>+#include <vector>++namespace veyra::sink {++// Compressed audio families the capture endpoint can expose. Data1 of the+// KSDATAFORMAT/WAVE subtype GUID is what identifies them on the wire.+enum class BitstreamKind { None, Ac3, Eac3, TrueHd, Dts, DtsHd };++// Maps a media-type subtype id to a family. Returns None for anything unknown+// (never guesses).+BitstreamKind classifyBitstreamSubtype(uint32_t subtypeData1);+const char* bitstreamKindName(BitstreamKind kind);+// Negotiation preference: higher wins when several compressed formats are+// offered (TrueHD Atmos > DD+ Atmos > DD+ > DTS-HD > DTS > AC-3).+int bitstreamPreferenceOrder(BitstreamKind kind);+// True when the subtype carries IEC 61937 framed bursts (S/PDIF style) that must+// be unwrapped before the codec parser sees them.+bool bitstreamIsIec61937(uint32_t subtypeData1);++class BitstreamDecoder {+public:+ BitstreamDecoder();+ ~BitstreamDecoder();+ BitstreamDecoder(const BitstreamDecoder&) = delete;+ BitstreamDecoder& operator=(const BitstreamDecoder&) = delete;++ // Opens the decoder for `kind`. `iec61937` unwraps S/PDIF bursts first.+ bool open(BitstreamKind kind, bool iec61937 = false);+ // Feeds raw bytes from the capture endpoint; decoded interleaved float+ // samples are appended to `out`. Returns false only on a hard failure, which+ // is also stored in lastError().+ bool push(const uint8_t* data, size_t bytes, std::vector<float>& out);+ // Drops codec state (seek / discontinuity): the next bytes start a new+ // stream, which is what happens when the console switches audio format.+ void reset();++ bool opened() const;+ unsigned channels() const;+ unsigned sampleRate() const;+ uint64_t decodedFrames() const;+ uint64_t decodedBytesIn() const;+ const std::string& lastError() const;++private:+ struct Impl;+ std::unique_ptr<Impl> p_;+};++} // namespace veyra::sinkdiff --git a/include/veyra/sink/CaptureAudioSession.h b/include/veyra/sink/CaptureAudioSession.hindex de00f050..b090d710 100644--- a/include/veyra/sink/CaptureAudioSession.h+++ b/include/veyra/sink/CaptureAudioSession.h@@ -11,6 +11,9 @@ struct CaptureAudioState {bool available=false,running=false,clockEstimated=true,limited=false;unsigned inputChannels=0,outputChannels=0;uint32_t inputChannelMask=0,outputChannelMask=0;uint32_t inputSampleRate=0;unsigned inputContainerBits=0,inputValidBits=0;bool inputFloating=false;+ // Non-empty when the input is a compressed bitstream (Dolby/DTS) that was+ // decoded to PCM before this session saw it, e.g. "E-AC-3/DD+".+ std::wstring inputBitstream;double compensationMs=0,bufferedMs=0,bufferHighWaterMs=0,endpointBufferedMs=0;double driftCorrectionPpm=0;uint64_t recoveryDiscardedFrames=0;@@ -42,6 +45,8 @@ public:// request the old audio reset explicitly.void videoReset(bool resetAudio=true);void setGain(float);+ // Records that the input arrived as a decoded bitstream (capture passthrough).+ void setInputBitstream(std::wstring kind);// 0 automatic, 1 manual, 2 off. Positive offset delays sound.void setSync(unsigned mode,int offsetMs);CaptureAudioState snapshot()const;diff --git a/src/sink/BitstreamAudio.cpp b/src/sink/BitstreamAudio.cppnew file mode 100644index 00000000..d5e317a7--- /dev/null+++ b/src/sink/BitstreamAudio.cpp@@ -0,0 +1,313 @@+#include "veyra/sink/BitstreamAudio.h"++#include "veyra/Log.h"++extern "C" {+#include <libavcodec/avcodec.h>+#include <libavutil/channel_layout.h>+#include <libswresample/swresample.h>+}++#include <cstring>++namespace veyra::sink {+namespace {++AVCodecID codecIdFor(BitstreamKind kind) {+ switch (kind) {+ case BitstreamKind::Ac3: return AV_CODEC_ID_AC3;+ case BitstreamKind::Eac3: return AV_CODEC_ID_EAC3;+ case BitstreamKind::TrueHd: return AV_CODEC_ID_TRUEHD;+ case BitstreamKind::Dts: return AV_CODEC_ID_DTS;+ case BitstreamKind::DtsHd: return AV_CODEC_ID_DTS;+ case BitstreamKind::None: break;+ }+ return AV_CODEC_ID_NONE;+}++// IEC 61937 burst: 4-byte sync (0xF8724E1F) + 2-byte data type + 2-byte length+// in bits, then the padded payload.+constexpr uint8_t kIecSync[4] = {0xF8, 0x72, 0x4E, 0x1F};+constexpr size_t kIecHeader = 8;++} // namespace++BitstreamKind classifyBitstreamSubtype(uint32_t subtypeData1) {+ switch (subtypeData1) {+ case 0x00000092u: return BitstreamKind::Ac3; // WAVE_FORMAT_DOLBY_AC3_SPDIF+ case 0x00002000u: return BitstreamKind::Ac3; // AC-3 in a WAVEFORMATEXTENSIBLE subtype+ case 0x0000000Au: return BitstreamKind::Eac3; // E-AC-3 / Dolby Digital Plus+ case 0x0000010Au: return BitstreamKind::Eac3; // DD+ carrying Atmos+ case 0x0000000Cu: return BitstreamKind::TrueHd; // TrueHD / MLP (Atmos over TrueHD)+ case 0x00000008u: return BitstreamKind::Dts; // DTS+ case 0x0000000Bu: return BitstreamKind::DtsHd; // DTS-HD+ case 0x0000010Bu: return BitstreamKind::DtsHd; // DTS:X (extension 1)+ case 0x0000030Bu: return BitstreamKind::DtsHd; // DTS:X (extension 2)+ default: return BitstreamKind::None;+ }+}++const char* bitstreamKindName(BitstreamKind kind) {+ switch (kind) {+ case BitstreamKind::Ac3: return "AC-3";+ case BitstreamKind::Eac3: return "E-AC-3/DD+";+ case BitstreamKind::TrueHd: return "TrueHD/MLP";+ case BitstreamKind::Dts: return "DTS";+ case BitstreamKind::DtsHd: return "DTS-HD";+ case BitstreamKind::None: break;+ }+ return "none";+}++int bitstreamPreferenceOrder(BitstreamKind kind) {+ switch (kind) {+ case BitstreamKind::TrueHd: return 60;+ case BitstreamKind::Eac3: return 50;+ case BitstreamKind::DtsHd: return 40;+ case BitstreamKind::Dts: return 30;+ case BitstreamKind::Ac3: return 20;+ case BitstreamKind::None: break;+ }+ return 0;+}++bool bitstreamIsIec61937(uint32_t subtypeData1) {+ return subtypeData1 == 0x00000092u; // S/PDIF framed AC-3 carrier+}++struct BitstreamDecoder::Impl {+ AVCodecContext* context = nullptr;+ AVCodecParserContext* parser = nullptr;+ SwrContext* resampler = nullptr;+ AVPacket* packet = nullptr;+ AVFrame* frame = nullptr;+ AVChannelLayout outLayout{};+ bool iec61937 = false;+ bool outLayoutValid = false;+ std::vector<uint8_t> iecPending;+ std::vector<uint8_t> parserScratch;+ std::string lastError;+ uint64_t frames = 0;+ uint64_t bytesIn = 0;++ ~Impl() { close(); }++ void close() {+ if (resampler != nullptr) swr_free(&resampler);+ if (frame != nullptr) av_frame_free(&frame);+ if (packet != nullptr) av_packet_free(&packet);+ if (parser != nullptr) av_parser_close(parser);+ if (context != nullptr) avcodec_free_context(&context);+ outLayoutValid = false;+ }++ // Appends the payload of every complete IEC 61937 burst to `out` and keeps+ // an incomplete tail for the next push.+ void unwrapIec61937(const uint8_t* data, size_t bytes, std::vector<uint8_t>& out) {+ size_t i = 0;+ while (i + kIecHeader <= bytes) {+ if (std::memcmp(data + i, kIecSync, 4) != 0) {+ // Not a burst header: treat the rest as raw codec data.+ out.insert(out.end(), data + i, data + bytes);+ return;+ }+ const size_t bits = size_t(data[i + 6]) | (size_t(data[i + 7]) << 8);+ const size_t payload = bits / 8;+ if (payload == 0) {+ i += kIecHeader;+ continue;+ }+ if (i + kIecHeader + payload > bytes) break; // incomplete burst+ out.insert(out.end(), data + i + kIecHeader, data + i + kIecHeader + payload);+ i += kIecHeader + payload;+ }+ if (i < bytes) iecPending.assign(data + i, data + bytes);+ }++ bool ensureResampler() {+ if (resampler != nullptr) return true;+ AVChannelLayout in{};+ if (av_channel_layout_copy(&in, &outLayout) < 0) {+ lastError = "channel layout copy failed";+ return false;+ }+ AVChannelLayout target{};+ if (av_channel_layout_copy(&target, &in) < 0) {+ av_channel_layout_uninit(&in);+ lastError = "channel layout copy failed";+ return false;+ }+ const int result = swr_alloc_set_opts2(&resampler, &target, AV_SAMPLE_FMT_FLT, context->sample_rate,+ &in, context->sample_fmt, context->sample_rate, 0, nullptr);+ av_channel_layout_uninit(&in);+ av_channel_layout_uninit(&target);+ if (result < 0 || resampler == nullptr || swr_init(resampler) < 0) {+ lastError = "swr_alloc_set_opts2/swr_init failed";+ if (resampler != nullptr) swr_free(&resampler);+ return false;+ }+ return true;+ }++ bool handleFrame(std::vector<float>& out) {+ if (!outLayoutValid) {+ if (av_channel_layout_copy(&outLayout, &frame->ch_layout) < 0) {+ lastError = "decoded frame has no usable channel layout";+ return false;+ }+ if (outLayout.order == AV_CHANNEL_ORDER_UNSPEC) {+ av_channel_layout_default(&outLayout, outLayout.nb_channels > 0 ? outLayout.nb_channels : 2);+ }+ outLayoutValid = true;+ }+ if (!ensureResampler()) return false;+ const unsigned channels = unsigned(outLayout.nb_channels);+ const size_t base = out.size();+ const int capacity = int(av_rescale_rnd(+ swr_get_delay(resampler, context->sample_rate) + frame->nb_samples,+ context->sample_rate, context->sample_rate, AV_ROUND_UP));+ out.resize(base + size_t(capacity) * channels);+ uint8_t* dstPlanes[1] = {reinterpret_cast<uint8_t*>(out.data() + base)};+ const int converted = swr_convert(resampler, dstPlanes, capacity,+ const_cast<const uint8_t**>(frame->extended_data), frame->nb_samples);+ if (converted < 0) {+ lastError = "swr_convert failed";+ return false;+ }+ out.resize(base + size_t(converted) * channels);+ frames += uint64_t(converted);+ return true;+ }++ bool decodePacket(std::vector<float>& out) {+ const int sent = avcodec_send_packet(context, packet);+ if (sent < 0 && sent != AVERROR(EAGAIN)) {+ lastError = "avcodec_send_packet failed";+ return false;+ }+ for (;;) {+ const int received = avcodec_receive_frame(context, frame);+ if (received == AVERROR(EAGAIN) || received == AVERROR_EOF) break;+ if (received < 0) {+ lastError = "avcodec_receive_frame failed";+ return false;+ }+ if (!handleFrame(out)) return false;+ }+ av_frame_unref(frame);+ return true;+ }+};++BitstreamDecoder::BitstreamDecoder() : p_(std::make_unique<Impl>()) {}+BitstreamDecoder::~BitstreamDecoder() = default;++bool BitstreamDecoder::open(BitstreamKind kind, bool iec61937) {+ auto& p = *p_;+ p.close();+ p.iec61937 = iec61937;+ p.lastError.clear();+ const AVCodecID codecId = codecIdFor(kind);+ if (codecId == AV_CODEC_ID_NONE) {+ p.lastError = "no decoder for this bitstream family";+ return false;+ }+ const AVCodec* codec = avcodec_find_decoder(codecId);+ if (codec == nullptr) {+ p.lastError = "this FFmpeg build has no decoder for the bitstream family";+ return false;+ }+ p.context = avcodec_alloc_context3(codec);+ if (p.context == nullptr || avcodec_open2(p.context, codec, nullptr) < 0) {+ p.lastError = "avcodec_open2 failed";+ p.close();+ return false;+ }+ p.parser = av_parser_init(codecId);+ p.packet = av_packet_alloc();+ p.frame = av_frame_alloc();+ if (p.packet == nullptr || p.frame == nullptr) {+ p.lastError = "packet/frame allocation failed";+ p.close();+ return false;+ }+ return true;+}++bool BitstreamDecoder::push(const uint8_t* data, size_t bytes, std::vector<float>& out) {+ auto& p = *p_;+ if (p.context == nullptr) return false;+ if (data == nullptr || bytes == 0) return true;+ p.bytesIn += bytes;++ const uint8_t* stream = data;+ size_t streamBytes = bytes;+ if (p.iec61937) {+ std::vector<uint8_t> combined;+ if (!p.iecPending.empty()) {+ combined.assign(p.iecPending.begin(), p.iecPending.end());+ p.iecPending.clear();+ }+ combined.insert(combined.end(), data, data + bytes);+ p.parserScratch.clear();+ p.unwrapIec61937(combined.data(), combined.size(), p.parserScratch);+ stream = p.parserScratch.data();+ streamBytes = p.parserScratch.size();+ if (streamBytes == 0) return true;+ }++ if (p.parser == nullptr) {+ // No parser for this codec (TrueHD): hand the buffer over as one packet.+ av_packet_unref(p.packet);+ if (av_new_packet(p.packet, int(streamBytes)) < 0) {+ p.lastError = "packet allocation failed";+ return false;+ }+ std::memcpy(p.packet->data, stream, streamBytes);+ return p.decodePacket(out);+ }++ size_t offset = 0;+ while (offset < streamBytes) {+ uint8_t* packetData = nullptr;+ int packetSize = 0;+ const int consumed = av_parser_parse2(p.parser, p.context, &packetData, &packetSize, stream + offset,+ int(streamBytes - offset), AV_NOPTS_VALUE, AV_NOPTS_VALUE, 0);+ if (consumed < 0) {+ p.lastError = "av_parser_parse2 failed";+ return false;+ }+ offset += size_t(consumed);+ if (packetSize <= 0) continue;+ av_packet_unref(p.packet);+ if (av_new_packet(p.packet, packetSize) < 0) {+ p.lastError = "packet allocation failed";+ return false;+ }+ std::memcpy(p.packet->data, packetData, size_t(packetSize));+ if (!p.decodePacket(out)) return false;+ }+ return true;+}++void BitstreamDecoder::reset() {+ auto& p = *p_;+ p.iecPending.clear();+ p.parserScratch.clear();+ if (p.context != nullptr) avcodec_flush_buffers(p.context);+ if (p.parser != nullptr) av_parser_close(p.parser);+ if (p.context != nullptr) p.parser = av_parser_init(p.context->codec_id);+}++bool BitstreamDecoder::opened() const { return p_->context != nullptr; }+unsigned BitstreamDecoder::channels() const {+ return p_->outLayoutValid ? unsigned(p_->outLayout.nb_channels) : 0;+}+unsigned BitstreamDecoder::sampleRate() const {+ return p_->context != nullptr ? unsigned(p_->context->sample_rate) : 0;+}+uint64_t BitstreamDecoder::decodedFrames() const { return p_->frames; }+uint64_t BitstreamDecoder::decodedBytesIn() const { return p_->bytesIn; }+const std::string& BitstreamDecoder::lastError() const { return p_->lastError; }++} // namespace veyra::sinkdiff --git a/src/sink/CaptureAudioSession.cpp b/src/sink/CaptureAudioSession.cppindex 62c637da..77802a29 100644--- a/src/sink/CaptureAudioSession.cpp+++ b/src/sink/CaptureAudioSession.cpp@@ -379,6 +379,10 @@ struct CaptureAudioSession::Impl : AudioPcmSource {};CaptureAudioSession::CaptureAudioSession():p_(std::make_unique<Impl>()){}CaptureAudioSession::~CaptureAudioSession(){stop();}+void CaptureAudioSession::setInputBitstream(std::wstring kind){+ std::lock_guard lock(p_->mutex);+ p_->state.inputBitstream=std::move(kind);+}bool CaptureAudioSession::configure(const WavePcmFormat& parsed){if(p_->thread.joinable()||!parsed.layout.valid()||!parsed.validBits)return false;p_->format=parsed.wave;p_->layout=parsed.layout;p_->validBits=parsed.validBits;p_->floating=parsed.floating;diff --git a/src/source/CaptureCardSource.cpp b/src/source/CaptureCardSource.cppindex 5b74c735..00e44e3b 100644--- a/src/source/CaptureCardSource.cpp+++ b/src/source/CaptureCardSource.cpp@@ -6,6 +6,7 @@#include "veyra/pipeline/ColorMetadata.h"#include "veyra/Log.h"#include "veyra/sink/AudioFormat.h"+#include "veyra/sink/BitstreamAudio.h"#include <windows.h>#include <dshow.h>#include <dvdmedia.h>@@ -125,6 +126,12 @@ struct CaptureCardSource::Impl:ISampleGrabberCB {float lastAudioGain=-1;bool audioGainSupported=false;ComPtr<IBaseFilter> audioSink;ComPtr<IReferenceClock> referenceClock;std::unique_ptr<sink::CaptureAudioSession> audioSession;+ // Dolby/DTS passthrough: when the device offers only compressed media types+ // 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;+ bool audioSessionDeferred=false;+ std::wstring audioBitstreamKind;std::unique_ptr<WasapiAudioInput> wasapi;std::wstring audioError;AudioInputRecovery audioRecovery;@@ -329,7 +336,7 @@ bool CaptureCardSource::connectDirectShowAudio(const SourceOpenDesc& desc){// commonly stereo first even when native 5.1 is available.auto releaseType=[](AM_MEDIA_TYPE* type){freeType(type);};using AudioType=std::unique_ptr<AM_MEDIA_TYPE,decltype(releaseType)>;-std::vector<AudioType> audioTypes;unsigned typeIndex=0;+std::vector<AudioType> audioTypes;std::vector<AudioType> bitstreamTypes;unsigned typeIndex=0;// Dolby/DTS bitstream capability probe: the capture card may expose AC-3 /// E-AC-3 (Dolby Digital Plus, includes Atmos over DD+) / TrueHD / DTS instead// of PCM. Veyra currently consumes PCM only, so a compressed stream is reported@@ -357,7 +364,7 @@ if(!supported){const char* name=bitstreamName(type->subtype);if(name){++bitstreamTypeCount;if(!bitstreamSummary.empty())bitstreamSummary+=",";bitstreamSummary+=name;- log::info("capture-audio-bitstream",std::string("mediaType=")+std::to_string(typeIndex)+" subtype=0x"+std::format("{:08X}",unsigned(type->subtype.Data1))+" kind="+name+" (not consumed yet)");+ log::info("capture-audio-bitstream",std::string("mediaType=")+std::to_string(typeIndex)+" subtype=0x"+std::format("{:08X}",unsigned(type->subtype.Data1))+" kind="+name+" (passthrough candidate)");}}if(type->formattype==FORMAT_WaveFormatEx&&type->pbFormat&&type->cbFormat>=sizeof(WAVEFORMATEX)){@@ -365,6 +372,7 @@ if(name){log::info("capture-audio",std::format("mediaType={} major=0x{:08X} subtype=0x{:08X} tag={} channels={} mask=0x{:X} rate={} containerBits={} validBits={} floating={} pcm={}",typeIndex++,type->majortype.Data1,type->subtype.Data1,wave->wFormatTag,wave->nChannels,supported?pcm.layout.mask:0,wave->nSamplesPerSec,wave->wBitsPerSample,supported?pcm.validBits:0,supported&&pcm.floating?1:0,supported?1:0));}else log::info("capture-audio",std::format("mediaType={} major=0x{:08X} subtype=0x{:08X} format=0x{:08X} pcm=0",typeIndex++,type->majortype.Data1,type->subtype.Data1,type->formattype.Data1));if(supported)audioTypes.push_back(std::move(owned));+ else if(bitstreamName(type->subtype))bitstreamTypes.push_back(std::move(owned));}log::info("capture-audio-bitstream",std::format("device bitstream types={} [{}] pcmTypes={}",bitstreamTypeCount,bitstreamSummary.empty()?"none":bitstreamSummary,audioTypes.size()));if(audioTypes.empty()){log::warn("capture-audio","audio pin has no supported PCM media type");return false;}@@ -397,11 +405,77 @@ if(audioTypes.empty()){log::warn("capture-audio","audio pin has no supported PCM}if(connectedAudio)break;}+ // Dolby/DTS passthrough fallback: no PCM type connected, so take the best+ // compressed type the device offers and decode it back to PCM. This is the+ // path a PS5 feeding Dolby Atmos / Dolby Audio / DTS needs.+ if(!connectedAudio&&!bitstreamTypes.empty()){+ std::stable_sort(bitstreamTypes.begin(),bitstreamTypes.end(),[](const auto& a,const auto& b){+ return sink::bitstreamPreferenceOrder(sink::classifyBitstreamSubtype(a->subtype.Data1))>+ sink::bitstreamPreferenceOrder(sink::classifyBitstreamSubtype(b->subtype.Data1));+ });+ for(const auto& owned:bitstreamTypes){+ auto* type=owned.get();+ const auto kind=sink::classifyBitstreamSubtype(type->subtype.Data1);+ const bool iec=sink::bitstreamIsIec61937(type->subtype.Data1);+ 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());+ continue;+ }+ auto session=std::make_unique<sink::CaptureAudioSession>();+ ComPtr<IBaseFilter> candidate;ComPtr<IPin> terminal;+ auto* target=session.get();+ auto pcmBuffer=std::make_shared<std::vector<float>>();+ auto started=std::make_shared<bool>(false);+ const std::string kindName=sink::bitstreamKindName(kind);+ const std::wstring kindWide(kindName.begin(),kindName.end());+ hr=createNativeAudioSink(*type,[target,decoder,pcmBuffer,started,kindWide](IMediaSample* sample){+ BYTE* bytes=nullptr;REFERENCE_TIME begin=0,end=0;+ if(FAILED(sample->GetPointer(&bytes))||FAILED(sample->GetTime(&begin,&end)))return VFW_E_SAMPLE_TIME_NOT_SET;+ pcmBuffer->clear();+ if(!decoder->push(bytes,size_t(sample->GetActualDataLength()),*pcmBuffer))return S_OK;+ if(pcmBuffer->empty())return S_OK;+ const unsigned channels=decoder->channels();+ const unsigned rate=decoder->sampleRate();+ if(channels==0||rate==0)return S_OK;+ if(!*started){+ WAVEFORMATEXTENSIBLE wfx{};+ wfx.Format.wFormatTag=WAVE_FORMAT_EXTENSIBLE;+ wfx.Format.nChannels=WORD(channels);+ wfx.Format.nSamplesPerSec=rate;+ wfx.Format.wBitsPerSample=32;+ wfx.Format.nBlockAlign=WORD(channels*4);+ wfx.Format.nAvgBytesPerSec=rate*channels*4;+ wfx.Format.cbSize=sizeof(WAVEFORMATEXTENSIBLE)-sizeof(WAVEFORMATEX);+ wfx.Samples.wValidBitsPerSample=32;+ // Standard layouts: 6 = 5.1, 8 = 7.1, otherwise 5.1 as the safe default.+ wfx.dwChannelMask=channels==8?0x63Fu:channels==6?0x3Fu:channels==2?0x3u:0x3Fu;+ wfx.SubFormat=KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;+ if(!target->configure(wfx.Format,sizeof(wfx))||!target->start())return E_FAIL;+ target->setInputBitstream(kindWide);+ *started=true;+ }+ return target->push(pcmBuffer->data(),pcmBuffer->size()*sizeof(float),double(begin)/10000,sample->IsDiscontinuity()==S_OK)?S_OK:E_FAIL;+ },candidate,terminal);+ if(SUCCEEDED(hr))hr=p.graph->AddFilter(candidate.Get(),L"Veyra audio bitstream");+ if(SUCCEEDED(hr))hr=p.graph->ConnectDirect(audioPin.Get(),terminal.Get(),type);+ if(SUCCEEDED(hr)){+ p.audioSink=candidate;p.audioSession=std::move(session);p.audioBitstream=decoder;+ p.audioSessionDeferred=true;+ {const std::string name=sink::bitstreamKindName(kind);p.audioBitstreamKind.assign(name.begin(),name.end());}+ connectedAudio=true;+ log::info("capture-audio-bitstream",std::string("passthrough selected kind=")+sink::bitstreamKindName(kind)+(iec?" (IEC 61937)":"")+" -> decoded to PCM on the first frame");+ }else if(candidate)p.graph->RemoveFilter(candidate.Get());+ log::info("capture-audio-bitstream",std::string("ConnectDirect hr=0x")+std::format("{:X}",unsigned(hr)));+ if(connectedAudio)break;+ }+ }return connectedAudio;}bool CaptureCardSource::start(){auto& p=*p_;if(p.info.opened)return true;if(!p.configured||!p.control)return false;- if(p.audioSession&&!p.audioSession->start())log::warn("capture-audio","audio start failed; retaining video capture");+ if(p.audioSession&&p.audioSessionDeferred)log::info("capture-audio-bitstream","audio session starts with the first decoded bitstream frame");+ else if(p.audioSession&&!p.audioSession->start())log::warn("capture-audio","audio start failed; retaining video capture");p.audioRecovery.reset(GetTickCount64());p.lastFrame=Impl::Clock::now();const auto hr=p.control->Run();p.info.opened=SUCCEEDED(hr);if(p.info.opened&&p.wasapi&&!p.wasapi->start())p.audioError=L"WASAPI 音频启动失败;视频继续运行";diff --git a/tools/bitstream_audio_test/main.cpp b/tools/bitstream_audio_test/main.cppnew file mode 100644index 00000000..3530f393--- /dev/null+++ b/tools/bitstream_audio_test/main.cpp@@ -0,0 +1,275 @@+// Dolby/DTS bitstream decode test (diagnostic; never shipped in the player).+//+// There is no bitstream-capable capture card on this machine, so the device path+// cannot be exercised. What CAN be proven locally is the decode half:+// 1. encode a 5.1 test signal with the same FFmpeg the player links,+// 2. feed the resulting AC-3 bitstream through veyra::sink::BitstreamDecoder+// in chunks (exercising the incremental parser path),+// 3. check the decoded channel count, frame count and per-channel amplitude+// ordering, so a wrong channel map or a silent decode fails loudly,+// 4. repeat with IEC 61937 burst framing (the S/PDIF carrier) to prove the+// unwrapper as well.+//+// Usage: veyra_bitstream_audio_test+#include <windows.h>++#include <cmath>+#include <cstdio>+#include <vector>++extern "C" {+#include <libavcodec/avcodec.h>+#include <libavutil/channel_layout.h>+}++#include "veyra/sink/BitstreamAudio.h"++using veyra::sink::BitstreamDecoder;+using veyra::sink::BitstreamKind;++namespace {++constexpr int kSampleRate = 48000;+constexpr int kChannels = 6;+constexpr int kSeconds = 2;+// Distinct per-channel amplitudes so a channel swap or a silent channel is+// visible in the decoded RMS. LFE gets a low tone because the encoder low-passes+// that channel.+constexpr double kAmplitudes[kChannels] = {0.50, 0.40, 0.30, 0.25, 0.20, 0.10};+constexpr double kTones[kChannels] = {440.0, 440.0, 440.0, 60.0, 440.0, 440.0};++// Encodes the test signal with libavcodec; returns the raw bitstream bytes.+bool encodeTestStream(BitstreamKind kind, std::vector<uint8_t>& out, std::string& why) {+ const AVCodecID codecId = kind == BitstreamKind::Ac3 ? AV_CODEC_ID_AC3 : AV_CODEC_ID_EAC3;+ const AVCodec* codec = avcodec_find_encoder(codecId);+ if (codec == nullptr) {+ why = "this FFmpeg build has no AC-3/E-AC-3 encoder (decoders only)";+ return false;+ }+ AVCodecContext* context = avcodec_alloc_context3(codec);+ if (context == nullptr) {+ why = "encoder context allocation failed";+ return false;+ }+ context->sample_rate = kSampleRate;+ context->bit_rate = kind == BitstreamKind::Ac3 ? 448000 : 640000;+ av_channel_layout_default(&context->ch_layout, kChannels);+ // FFmpeg n9 no longer exposes AVCodec::sample_fmts, so probe the formats the+ // AC-3/E-AC-3 encoders accept instead of advertising a preferred one.+ bool opened = false;+ for (AVSampleFormat format : {AV_SAMPLE_FMT_FLTP, AV_SAMPLE_FMT_S32P, AV_SAMPLE_FMT_S16P}) {+ context->sample_fmt = format;+ if (avcodec_open2(context, codec, nullptr) >= 0) { opened = true; break; }+ }+ if (!opened) {+ why = "avcodec_open2(encoder) failed for fltp/s32p/s16p";+ avcodec_free_context(&context);+ return false;+ }+ const int frameSize = context->frame_size > 0 ? context->frame_size : 1536;+ AVFrame* frame = av_frame_alloc();+ AVPacket* packet = av_packet_alloc();+ if (frame == nullptr || packet == nullptr) {+ why = "frame/packet allocation failed";+ avcodec_free_context(&context);+ av_frame_free(&frame);+ av_packet_free(&packet);+ return false;+ }+ frame->format = context->sample_fmt;+ frame->sample_rate = context->sample_rate;+ frame->nb_samples = frameSize;+ if (av_channel_layout_copy(&frame->ch_layout, &context->ch_layout) < 0 ||+ av_frame_get_buffer(frame, 0) < 0) {+ why = "frame buffer allocation failed";+ avcodec_free_context(&context);+ av_frame_free(&frame);+ av_packet_free(&packet);+ return false;+ }+ const int totalFrames = kSampleRate * kSeconds;+ int produced = 0;+ bool ok = true;+ while (produced < totalFrames && ok) {+ if (av_frame_make_writable(frame) < 0) {+ why = "av_frame_make_writable failed";+ ok = false;+ break;+ }+ const bool planar = av_sample_fmt_is_planar(context->sample_fmt) == 1;+ for (int ch = 0; ch < kChannels && ok; ++ch) {+ auto* plane = reinterpret_cast<float*>(frame->data[planar ? ch : 0]);+ for (int i = 0; i < frameSize; ++i) {+ const double t = double(produced + i) / kSampleRate;+ const float value = float(kAmplitudes[ch] * std::sin(2.0 * 3.14159265358979323846 * kTones[ch] * t));+ if (planar) plane[i] = value;+ else plane[size_t(i) * kChannels + ch] = value;+ }+ }+ produced += frameSize;+ if (avcodec_send_frame(context, frame) < 0) {+ why = "avcodec_send_frame failed";+ ok = false;+ break;+ }+ for (;;) {+ const int received = avcodec_receive_packet(context, packet);+ if (received == AVERROR(EAGAIN) || received == AVERROR_EOF) break;+ if (received < 0) {+ why = "avcodec_receive_packet failed";+ ok = false;+ break;+ }+ out.insert(out.end(), packet->data, packet->data + packet->size);+ av_packet_unref(packet);+ }+ }+ if (ok) {+ avcodec_send_frame(context, nullptr);+ for (;;) {+ const int received = avcodec_receive_packet(context, packet);+ if (received < 0) break;+ out.insert(out.end(), packet->data, packet->data + packet->size);+ av_packet_unref(packet);+ }+ }+ avcodec_free_context(&context);+ av_frame_free(&frame);+ av_packet_free(&packet);+ if (!ok || out.empty()) {+ if (why.empty()) why = "encoder produced no data";+ return false;+ }+ return true;+}++// Wraps raw AC-3 bytes into IEC 61937 bursts (8-byte header + padded payload).+std::vector<uint8_t> toIec61937(const std::vector<uint8_t>& raw) {+ std::vector<uint8_t> out;+ // 6144 bytes is the standard S/PDIF burst payload size for AC-3.+ const size_t burst = 6144;+ for (size_t offset = 0; offset < raw.size(); offset += burst) {+ const size_t chunk = (std::min)(burst, raw.size() - offset);+ const size_t padded = (chunk + 1) & ~size_t{1};+ const size_t headerSize = out.size();+ out.resize(headerSize + 8, 0);+ out[headerSize + 0] = 0xF8;+ out[headerSize + 1] = 0x72;+ out[headerSize + 2] = 0x4E;+ out[headerSize + 3] = 0x1F;+ out[headerSize + 4] = 0x00; // data type: AC-3+ out[headerSize + 5] = 0x00;+ const uint16_t bits = uint16_t((chunk * 8) & 0xFFFF);+ out[headerSize + 6] = uint8_t(bits & 0xFF);+ out[headerSize + 7] = uint8_t(bits >> 8);+ out.insert(out.end(), raw.begin() + offset, raw.begin() + offset + chunk);+ out.resize(out.size() + (padded - chunk), 0);+ }+ return out;+}++struct DecodeResult {+ bool ok = false;+ unsigned channels = 0;+ uint64_t frames = 0;+ std::vector<double> rms;+ std::string error;+};++DecodeResult decodeStream(const std::vector<uint8_t>& bytes, BitstreamKind kind, bool iec61937, int chunks) {+ DecodeResult result{};+ BitstreamDecoder decoder;+ if (!decoder.open(kind, iec61937)) {+ result.error = decoder.lastError();+ return result;+ }+ std::vector<float> pcm;+ const size_t perChunk = bytes.size() / size_t(chunks > 0 ? chunks : 1);+ for (size_t offset = 0; offset < bytes.size();) {+ const size_t take = (std::min)(perChunk == 0 ? bytes.size() : perChunk, bytes.size() - offset);+ if (!decoder.push(bytes.data() + offset, take, pcm)) {+ result.error = decoder.lastError();+ return result;+ }+ offset += take;+ }+ result.channels = decoder.channels();+ result.frames = decoder.decodedFrames();+ if (result.channels == 0 || result.frames == 0) {+ result.error = "decoder produced no audio";+ return result;+ }+ result.rms.assign(result.channels, 0.0);+ const uint64_t frames = result.frames;+ for (uint64_t frame = 0; frame < frames; ++frame) {+ for (unsigned ch = 0; ch < result.channels; ++ch) {+ const float sample = pcm[size_t(frame) * result.channels + ch];+ result.rms[ch] += double(sample) * double(sample);+ }+ }+ for (auto& value : result.rms) value = std::sqrt(value / double(frames));+ result.ok = true;+ return result;+}++void report(const char* label, const DecodeResult& result) {+ std::printf("[bitstream-test] %s channels=%u frames=%llu", label, result.channels,+ static_cast<unsigned long long>(result.frames));+ for (size_t i = 0; i < result.rms.size(); ++i) std::printf(" ch%zu=%.4f", i, result.rms[i]);+ std::printf("%s%s\n", result.error.empty() ? "" : " error=", result.error.c_str());+}++// The five non-LFE channels must keep the encoded amplitude ordering; the LFE+// (channel 3) is low-passed by the encoder, so it is only checked for presence.+bool amplitudeOrderingHolds(const DecodeResult& result) {+ if (result.rms.size() != kChannels) return false;+ const int order[kChannels - 1] = {0, 1, 2, 4}; // compare 0>1>2>4>5+ for (int i = 0; i < 4; ++i) {+ const double higher = result.rms[order[i]];+ const double lower = i == 3 ? result.rms[5] : result.rms[order[i + 1]];+ if (!(higher > lower * 1.05)) return false;+ }+ return result.rms[3] > 0.005;+}++} // namespace++int main() {+ setvbuf(stdout, nullptr, _IONBF, 0);+ std::printf("[bitstream-test] ffmpeg avcodec=%u swresample linked, decoders: ac3=%d eac3=%d dts=%d truehd=%d\n",+ avcodec_version(),+ avcodec_find_decoder(AV_CODEC_ID_AC3) ? 1 : 0,+ avcodec_find_decoder(AV_CODEC_ID_EAC3) ? 1 : 0,+ avcodec_find_decoder(AV_CODEC_ID_DTS) ? 1 : 0,+ avcodec_find_decoder(AV_CODEC_ID_TRUEHD) ? 1 : 0);++ bool ok = true;+ for (BitstreamKind kind : {BitstreamKind::Ac3, BitstreamKind::Eac3}) {+ std::vector<uint8_t> bitstream;+ std::string why;+ if (!encodeTestStream(kind, bitstream, why)) {+ std::printf("[bitstream-test] %s encode skipped: %s\n", veyra::sink::bitstreamKindName(kind), why.c_str());+ ok = false;+ continue;+ }+ std::printf("[bitstream-test] %s encoded bytes=%llu\n", veyra::sink::bitstreamKindName(kind),+ static_cast<unsigned long long>(bitstream.size()));+ const auto raw = decodeStream(bitstream, kind, false, 3);+ report(veyra::sink::bitstreamKindName(kind), raw);+ if (!raw.ok || raw.channels != kChannels || !amplitudeOrderingHolds(raw)) {+ std::printf("[bitstream-test] FAIL %s: decode/channel/amplitude check\n", veyra::sink::bitstreamKindName(kind));+ ok = false;+ }+ if (kind == BitstreamKind::Ac3) {+ const auto framed = decodeStream(toIec61937(bitstream), kind, true, 2);+ report("AC-3 (IEC 61937)", framed);+ if (!framed.ok || framed.channels != kChannels || !amplitudeOrderingHolds(framed)) {+ std::printf("[bitstream-test] FAIL AC-3 IEC 61937 unwrap/decode\n");+ ok = false;+ }+ }+ }+ std::printf("[bitstream-test] VERDICT %s\n", ok ? "bitstream decode + channel mapping verified locally"+ : "bitstream decode verification incomplete");+ return ok ? 0 : 1;+}