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++
Fix VRR eligibility and pro status wrapping; add URL playback and file deinterlacing
Veyra Goal Agent31fa17b412a7
diff --git a/CMakeLists.txt b/CMakeLists.txtindex 5ca3abed..89ef4354 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -496,6 +496,7 @@ if(VEYRA_FFMPEG_ROOT AND EXISTS "${VEYRA_FFMPEG_ROOT}/include/libavformat/avformadd_library(veyra_media STATICsrc/media/FFmpegDemuxer.cppsrc/media/FFmpegVideoDecoder.cpp+ src/media/FFmpegDeinterlacer.cpp)veyra_apply_warnings(veyra_media)# FFmpeg headers are third-party; /WX stays off for this target@@ -656,6 +657,10 @@ if(VEYRA_FFMPEG_ROOT AND EXISTS "${VEYRA_FFMPEG_ROOT}/include/libavformat/avformtarget_link_libraries(veyra_source_tests PRIVATE veyra_sources)add_executable(veyra_capture_tests tests/integration/CaptureSourceTests.cpp)+ add_executable(veyra_network_interlace_tests tests/integration/NetworkInterlaceTests.cpp)+ target_compile_features(veyra_network_interlace_tests PRIVATE cxx_std_20)+ target_compile_definitions(veyra_network_interlace_tests PRIVATE UNICODE _UNICODE WIN32_LEAN_AND_MEAN NOMINMAX)+ target_link_libraries(veyra_network_interlace_tests PRIVATE veyra_engine)add_executable(veyra_decklink_tests tests/unit/DeckLinkCaptureTests.cpp)target_compile_features(veyra_decklink_tests PRIVATE cxx_std_20)target_compile_definitions(veyra_decklink_tests PRIVATE NOMINMAX WIN32_LEAN_AND_MEAN)diff --git a/i18n/catalog.json b/i18n/catalog.jsonindex 3dbda0c0..7e900594 100644--- a/i18n/catalog.json+++ b/i18n/catalog.json@@ -2303,6 +2303,13 @@"en": "{}×{} · tiled NR (no whole-image context) · saved at full size","ja": "{}×{} · 分割 NR(画像全体の文脈なし)· 保存は元のサイズ"},+ {+ "zh": "{}去隔行:{} · {:.3f}i → {:.3f}p",+ "src": "src/engine/EngineController.cpp",+ "zh-TW": "{}去交錯:{} · {:.3f}i → {:.3f}p",+ "en": "{}Deinterlacing: {} · {:.3f}i → {:.3f}p",+ "ja": "{}インターレース解除:{} · {:.3f}i → {:.3f}p"+ },{"zh": "{}失败(错误 {})","src": "src/engine/VideoExportJob.cpp",@@ -3599,6 +3606,13 @@"en": "In compatible mode, turn off the mouse pointer or use Windows capture","ja": "互換モードではマウスポインターをオフにするか、Windows キャプチャーを使ってください"},+ {+ "zh": "兼容软解",+ "src": "src/engine/EngineController.cpp",+ "zh-TW": "相容軟解",+ "en": "software compatibility",+ "ja": "互換ソフトウェア"+ },{"zh": "内容节奏","src": "qml/NodePage.qml",@@ -4292,6 +4306,34 @@"en": "Pair","ja": "ペアリングへ"},+ {+ "zh": "去隔行处理失败,请查看诊断",+ "src": "src/source/MediaFileSource.cpp",+ "zh-TW": "去交錯處理失敗,請查看診斷",+ "en": "Deinterlacing failed. See diagnostics.",+ "ja": "インターレース解除に失敗しました。診断を確認してください。"+ },+ {+ "zh": "去隔行尾帧输出失败",+ "src": "src/source/MediaFileSource.cpp",+ "zh-TW": "去交錯尾幀輸出失敗",+ "en": "Could not drain the final deinterlaced frames.",+ "ja": "末尾フレームのインターレース解除に失敗しました。"+ },+ {+ "zh": "去隔行组件不可用或不支持当前格式;请关闭去隔行或改用软解",+ "src": "src/source/MediaFileSource.cpp",+ "zh-TW": "去交錯元件不可用或不支援目前格式;請關閉去交錯或改用軟解",+ "en": "The deinterlacing component is missing or this format is unsupported. Disable deinterlacing or select software decoding.",+ "ja": "インターレース解除コンポーネントがないか形式が非対応です。解除をオフにするかソフトウェアデコードを選択してください。"+ },+ {+ "zh": "去隔行输出失败,请查看诊断",+ "src": "src/source/MediaFileSource.cpp",+ "zh-TW": "去交錯輸出失敗,請查看診斷",+ "en": "Deinterlaced output failed. See diagnostics.",+ "ja": "インターレース解除の出力に失敗しました。診断を確認してください。"+ },{"zh": "参数化亮调","src": "src/ui/QmlPlayerBridge.cpp",@@ -4495,6 +4537,13 @@"en": "Only shadows below this level are lifted","ja": "この輝度以下の暗部にのみ効く"},+ {+ "zh": "只处理标记为隔行的视频,优先使用 GPU;软解使用兼容算法。下次打开视频生效。",+ "src": "qml/SettingsPage.qml",+ "zh-TW": "只處理標記為隔行的影片,優先使用 GPU;軟解使用相容演算法。下次開啟影片生效。",+ "en": "Processes only video marked as interlaced, using the GPU when decoding on hardware. Software decoding uses a compatible filter. Applies when you next open a video.",+ "ja": "インターレースと記録された動画のみ処理します。ハードウェアデコード時は GPU、ソフトウェアデコード時は互換フィルターを使用します。次に動画を開くと適用されます。"+ },{"zh": "只有节点模式使用编辑连接","src": "src/engine/EffectChain.cpp",@@ -4558,13 +4607,6 @@"en": "Variable refresh · unavailable on this display","ja": "可変リフレッシュ · このディスプレイでは使用不可"},- {- "zh": "可变刷新 · 未生效",- "src": "src/ui/QmlPlayerBridge.cpp",- "zh-TW": "可變更新 · 未生效",- "en": "Variable refresh · not active",- "ja": "可変リフレッシュ · 未動作"- },{"zh": "可变刷新 · 生效中","src": "src/ui/QmlPlayerBridge.cpp",@@ -4572,6 +4614,13 @@"en": "Variable refresh · active","ja": "可変リフレッシュ · 動作中"},+ {+ "zh": "可变刷新 · 等待驱动确认",+ "src": "src/ui/QmlPlayerBridge.cpp",+ "zh-TW": "可變更新率 · 等待驅動確認",+ "en": "Variable refresh · awaiting driver confirmation",+ "ja": "可変リフレッシュ · ドライバーの確認待ち"+ },{"zh": "可变刷新:超过屏幕最高刷新时只排 1 帧 · ","src": "src/engine/VideoPresenter.cpp",@@ -6267,11 +6316,11 @@"ja": "画面キャプチャー…"},{- "zh": "屏幕支持,但驱动未开启:NVIDIA 控制面板 → 设置 G-SYNC",+ "zh": "屏幕支持可变刷新,但当前显示模式不可用;请检查连接、刷新率及驱动设置","src": "src/ui/QmlPlayerBridge.cpp",- "zh-TW": "螢幕支援,但驅動程式未開啟:NVIDIA 控制面板 → 設定 G-SYNC",- "en": "The display supports it, but the driver has it off: NVIDIA Control Panel → Set up G-SYNC",- "ja": "ディスプレイは対応していますが、ドライバーで無効です:NVIDIA コントロールパネル → G-SYNC の設定"+ "zh-TW": "螢幕支援可變更新率,但目前顯示模式不可用;請檢查連接、更新率及驅動設定",+ "en": "The display supports VRR, but it is unavailable in the current display mode. Check the connection, refresh rate and driver settings.",+ "ja": "画面は VRR 対応ですが現在の表示モードでは使用できません。接続、リフレッシュレート、ドライバー設定を確認してください。"},{"zh": "屏幕正处于可变刷新(驱动已开启)",@@ -6638,18 +6687,11 @@"ja": "オン · 強度 "},{- "zh": "已开启,屏幕还没进入可变刷新:全屏并隐藏控制栏,或在 NVIDIA 控制面板为窗口模式开启 G-SYNC",- "src": "src/ui/QmlPlayerBridge.cpp",- "zh-TW": "已開啟,螢幕還沒進入可變更新:全螢幕並隱藏控制列,或在 NVIDIA 控制面板為視窗模式開啟 G-SYNC",- "en": "On, but the display is not in variable refresh yet: go fullscreen with the controls hidden, or enable G-SYNC for windowed mode in the NVIDIA Control Panel",- "ja": "オンですが、まだ可変リフレッシュになっていません:全画面でコントロールバーを隠すか、NVIDIA コントロールパネルでウィンドウモードの G-SYNC を有効にしてください"- },- {- "zh": "已开启,播放时生效",+ "zh": "已开启,将在播放时请求可变刷新;是否生效以驱动报告为准","src": "src/ui/QmlPlayerBridge.cpp",- "zh-TW": "已開啟,播放時生效",- "en": "On; applies during playback",- "ja": "オン(再生中に有効)"+ "zh-TW": "已開啟,將在播放時請求可變更新率;是否生效以驅動回報為準",+ "en": "Enabled. VRR will be requested during playback; activation is confirmed by the driver.",+ "ja": "有効です。再生時に VRR を要求します。動作状態はドライバーの報告で確認します。"},{"zh": "已开启:%1",@@ -6805,6 +6847,13 @@"en": "Asked the host to quit the game.","ja": "ホストにゲームの終了を要求しました。"},+ {+ "zh": "已请求可变刷新,驱动尚未确认生效;可检查窗口/全屏 G-SYNC 设置,当前状态不代表驱动已关闭",+ "src": "src/ui/QmlPlayerBridge.cpp",+ "zh-TW": "已請求可變更新率,驅動尚未確認生效;可檢查視窗/全螢幕 G-SYNC 設定,目前狀態不代表驅動已關閉",+ "en": "VRR presentation requested; the driver has not confirmed activation. Check windowed/fullscreen G-SYNC settings. This does not mean the driver setting is off.",+ "ja": "VRR 表示を要求しましたが、ドライバーはまだ動作を確認していません。ウィンドウ/全画面の G-SYNC 設定を確認できます。この状態は設定がオフという意味ではありません。"+ },{"zh": "已达到导入上限(最多10000项),其余文件未添加","src": "src/ui/PlaylistModel.cpp",@@ -7647,7 +7696,7 @@},{"zh": "打开",- "src": "qml/SettingsPage.qml",+ "src": "qml/DialogHost.qml","zh-TW": "開啟","en": "Open","ja": "開く"@@ -8108,6 +8157,20 @@"en": "Could not read playlist; using an empty list.","ja": "プレイリストを読み込めないため、空のリストを使用します。"},+ {+ "zh": "播放地址",+ "src": "qml/DialogHost.qml",+ "zh-TW": "播放位址",+ "en": "Open media URL",+ "ja": "URL を開く"+ },+ {+ "zh": "播放地址…",+ "src": "qml/CineBar.qml",+ "zh-TW": "播放位址…",+ "en": "Open media URL…",+ "ja": "URL を開く…"+ },{"zh": "播放失败","src": "qml/PlaylistWindow.qml",@@ -11083,6 +11146,13 @@"en": "The target must exceed the source size. Upscaling is skipped when the source already meets the target.","ja": "入力より大きい目標解像度が必要です。入力が目標以上の場合は超解像処理を行いません。"},+ {+ "zh": "直接打开 HTTP、HTTPS 或 RTSP 视频流,例如 IPTV 或摄像机地址",+ "src": "qml/DialogHost.qml",+ "zh-TW": "直接開啟 HTTP、HTTPS 或 RTSP 影片串流,例如 IPTV 或攝影機位址",+ "en": "Open an HTTP, HTTPS or RTSP media stream, such as IPTV or a camera feed.",+ "ja": "IPTV やカメラなどの HTTP、HTTPS、RTSP メディアストリームを開きます。"+ },{"zh": "直播兼容模式未能启用,已恢复","src": "src/engine/EngineControllerImage.cpp",@@ -11594,6 +11664,13 @@"en": "Decoder for this subtitle format is unavailable","ja": "この字幕形式のデコーダーがありません"},+ {+ "zh": "网络视频 · %1",+ "src": "src/ui/QmlPlayerBridge.cpp",+ "zh-TW": "網路影片 · %1",+ "en": "Network video · %1",+ "ja": "ネットワーク動画 · %1"+ },{"zh": "美乐威低延迟模式","src": "qml/DialogHost.qml",@@ -11734,6 +11811,13 @@"en": "Auto estimate: applies to live capture card / PS5 input","ja": "自動推定:キャプチャーカード / PS5 のライブ入力時に有効"},+ {+ "zh": "自动去隔行",+ "src": "qml/SettingsPage.qml",+ "zh-TW": "自動去交錯",+ "en": "Automatic deinterlacing",+ "ja": "自動インターレース解除"+ },{"zh": "自动参数分别适配风格 0/1/2。手动可独立保留颜色、亮度和暗部;保护会降低对应变化量。时域稳定复用光流,切换方式保留手动数值。","src": "qml/NrLayerEditor.qml",@@ -13015,6 +13099,13 @@"en": "Enter a speed between 0.25 and 4.00","ja": "0.25~4.00 の速度を入力してください"},+ {+ "zh": "请输入有效的 HTTP、HTTPS 或 RTSP 视频地址",+ "src": "src/ui/QmlPlayerBridge.cpp",+ "zh-TW": "請輸入有效的 HTTP、HTTPS 或 RTSP 影片位址",+ "en": "Enter a valid HTTP, HTTPS or RTSP media URL.",+ "ja": "有効な HTTP、HTTPS、RTSP メディア URL を入力してください。"+ },{"zh": "请选择","src": "qml/DialogHost.qml",@@ -14793,6 +14884,13 @@"en": "Interlaced","ja": "インターレース"},+ {+ "zh": "隔行视频画面损坏或尺寸改变,已停止处理",+ "src": "src/source/MediaFileSource.cpp",+ "zh-TW": "隔行影片畫面損毀或尺寸變更,已停止處理",+ "en": "The interlaced frame is corrupt or its dimensions changed. Processing stopped.",+ "ja": "インターレース動画のフレームが破損しているか寸法が変化したため、処理を停止しました。"+ },{"zh": "隔行({:.2f} 场/秒)","src": "src/source/CaptureCardSource.cpp",@@ -14912,6 +15010,13 @@"en": "Requires a hardware GPU with DirectX 12 support","ja": "DirectX 12 対応のハードウェア GPU が必要です"},+ {+ "zh": "需要直接媒体地址,普通网页或需要网页登录的页面不能直接播放。直播流通常无法拖动进度。",+ "src": "qml/DialogHost.qml",+ "zh-TW": "需要直接媒體位址,一般網頁或需要網頁登入的頁面無法直接播放。直播串流通常無法拖曳進度。",+ "en": "Use a direct media URL. Ordinary web pages and pages requiring browser sign-in cannot be played directly. Live streams usually do not support seeking.",+ "ja": "メディアの直接 URL が必要です。通常の Web ページやブラウザーでのログインが必要なページは直接再生できません。ライブ配信では通常シークできません。"+ },{"zh": "需要系统显示事件才能测得真实值;取不到时显示未测","src": "qml/ProPage.qml",diff --git a/include/veyra/engine/EngineController.h b/include/veyra/engine/EngineController.hindex 4336785f..eda1dc44 100644--- a/include/veyra/engine/EngineController.h+++ b/include/veyra/engine/EngineController.h@@ -43,6 +43,7 @@ struct PlayerOptions { bool nr=false,sr=false,fg=false,realtime=true; uint32_t fbool captureReplayForTest=false; // file-backed live scheduler test; never enabled by UIbool captureCpuUnpack=false; // N1 diagnostic: legacy per-pixel CPU unpackbool softwareDecode=false; // user setting: files skip D3D12VA and decode on the CPU+ bool deinterlace=true; // automatic file deinterlace, preserves progressive bypassbool hardwareDecodeOnly=false; // user setting "强制硬解": files fail instead of falling back to softwareEnhancementSettings snapshot()const{auto s=settings;s.nr=nr;s.sr=sr;s.multiplier=fg?fgMultiplier:1;s.nrPolicy=realtime?(settings.nrPolicy==pipeline::NrSizePolicy::Native?pipeline::NrSizePolicy::Realtime:settings.nrPolicy):pipeline::NrSizePolicy::Native;return s;}static PlayerOptions from(EnhancementSettings s,std::optional<ChainRuntimeOrder> order=std::nullopt){PlayerOptions o;o.nr=s.nr;o.sr=s.sr;o.fg=s.multiplier>1;o.fgMultiplier=std::max(2u,s.multiplier);o.realtime=s.nrPolicy!=pipeline::NrSizePolicy::Native;o.settings=s;o.nodeOrder=order;return o;}diff --git a/include/veyra/gfx/NvidiaVrr.h b/include/veyra/gfx/NvidiaVrr.hindex f1dcd12b..d5ec5490 100644--- a/include/veyra/gfx/NvidiaVrr.h+++ b/include/veyra/gfx/NvidiaVrr.h@@ -31,13 +31,21 @@ struct VrrState {int status=0; // last NvAPI status (0 = OK)bool operator==(const VrrState&)const=default;};-// 0 unknown (no NVIDIA driver answer), 1 the monitor cannot do VRR, 2 it can-// but VRR is not possible now (driver setting off, mode or connection),-// 3 VRR possible/requested but not active, 4 VRR active on the display.+// A display may be capable before an application's VRR presentation starts.+// In particular G-SYNC Compatible can report all GetVRRInfo flags clear while+// generic monitor capabilities say that the applied mode supports VRR (#45).+// Permit the user's presentation request then, without inventing active flags+// or assuming that the NVIDIA Control Panel setting is off.+constexpr bool vrrPresentationAvailable(const VrrState& s){+ return s.enabled||s.inVrrMode||s.possible||s.requested+ ||(s.capsKnown&&s.supportsVrr&&s.currentlyCapable);+}+// 0 unknown, 1 unsupported, 2 supported but unavailable in the applied mode,+// 3 presentation may request VRR (activation unconfirmed), 4 driver reports active.constexpr unsigned vrrLevel(const VrrState& s){if(!s.known)return 0;if(s.enabled||s.inVrrMode)return 4;- if(s.possible||s.requested)return 3;+ if(vrrPresentationAvailable(s))return 3;if(s.supportsVrr||s.currentlyCapable)return 2;return 1;}@@ -47,7 +55,7 @@ inline VrrState queryVrr(HWND window){static const int testLevel=[]{wchar_t v[4]{};return GetEnvironmentVariableW(L"VEYRA_TEST_VRR_LEVEL",v,4)?std::clamp(_wtoi(v),0,4):-1;}();if(testLevel>=0){VrrState s;s.simulated=true;s.known=testLevel>0;s.capsKnown=s.known;- s.supportsVrr=s.currentlyCapable=testLevel>=2;s.possible=s.requested=testLevel>=3;s.enabled=s.inVrrMode=testLevel>=4;+ s.supportsVrr=testLevel>=2;s.currentlyCapable=testLevel>=3;s.possible=s.requested=testLevel>=3;s.enabled=s.inVrrMode=testLevel>=4;return s;}struct Info {uint32_t version;uint32_t flags;uint32_t reservedEx[4];};diff --git a/include/veyra/media/FFmpegDeinterlacer.h b/include/veyra/media/FFmpegDeinterlacer.hnew file mode 100644index 00000000..633b972a--- /dev/null+++ b/include/veyra/media/FFmpegDeinterlacer.h@@ -0,0 +1,24 @@+#pragma once+#include <memory>+#include <string>+struct AVFrame;+namespace veyra::media {+struct HardwareSurfaceView;+// Optional LGPL FFmpeg filter module. GPU surfaces stay on GPU; software+// decoded frames use bwdif. Sources own demux/decode/PTS and seek resets.+class FFmpegDeinterlacer {+public:+ FFmpegDeinterlacer();+ ~FFmpegDeinterlacer();+ bool open(const AVFrame*,const HardwareSurfaceView*,int tbNum,int tbDen,int fpsNum,int fpsDen);+ int push(const AVFrame*,const HardwareSurfaceView* = nullptr);+ int receive(const AVFrame**);+ int timeBaseNum()const;+ int timeBaseDen()const;+ bool active()const;+ const std::string& path()const;+ void close();+private:+ struct Impl;std::unique_ptr<Impl> impl_;+};+}diff --git a/include/veyra/media/FFmpegDemuxer.h b/include/veyra/media/FFmpegDemuxer.hindex 04c330bc..aa9075aa 100644--- a/include/veyra/media/FFmpegDemuxer.h+++ b/include/veyra/media/FFmpegDemuxer.h@@ -5,6 +5,7 @@#include <cstdint>#include <string>+#include "veyra/media/NetworkInput.h"struct AVFormatContext;struct AVCodecParameters;@@ -27,12 +28,13 @@ public:FFmpegDemuxer(const FFmpegDemuxer&) = delete;FFmpegDemuxer& operator=(const FFmpegDemuxer&) = delete;- bool open(const std::wstring& path);+ bool open(const std::wstring& path,const std::atomic<bool>* cancelled=nullptr);void close();bool opened() const { return context_ != nullptr; }int videoStreamIndex() const { return videoStreamIndex_; }int64_t durationUs() const;+ bool seekable() const;double averageFps() const; // informational only; the pipeline is PTS-drivenint nominalRateNum() const;int nominalRateDen() const;@@ -64,6 +66,7 @@ private:int videoStreamIndex_ = -1;DemuxerStats stats_{};bool havePendingPacket_ = false;+ InputInterrupt interrupt_;};} // namespace veyra::mediadiff --git a/include/veyra/media/NetworkInput.h b/include/veyra/media/NetworkInput.hnew file mode 100644index 00000000..d17203bd--- /dev/null+++ b/include/veyra/media/NetworkInput.h@@ -0,0 +1,39 @@+#pragma once+#include <atomic>+#include <chrono>+#include <cwctype>+#include <string>+#include <string_view>+#include <mutex>+extern "C" {+#include <libavformat/avformat.h>+}+namespace veyra::media {+inline bool networkMediaInput(std::wstring_view path) {+ const auto colon=path.find(L':');+ if(colon==std::wstring_view::npos||colon>5)return false;+ std::wstring scheme(path.substr(0,colon));+ for(auto& ch:scheme)ch=std::towlower(ch);+ return scheme==L"http"||scheme==L"https"||scheme==L"rtsp";+}+// Per-operation deadlines only on networks; immediate owner cancellation on all inputs.+class InputInterrupt {+public:+ void configure(bool network,const std::atomic<bool>* owner,const std::atomic<bool>* local=nullptr){network_=network;owner_=owner;local_=local;deadline_=0;}+ void arm(){deadline_=network_?now()+5000000000ll:0;}+ void disarm(){deadline_=0;}+ static int callback(void* opaque){+ const auto& self=*static_cast<InputInterrupt*>(opaque);const auto deadline=self.deadline_.load();+ return (self.owner_&&self.owner_->load())||(self.local_&&self.local_->load())||(deadline&&now()>=deadline);+ }+private:+ static int64_t now(){return std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::steady_clock::now().time_since_epoch()).count();}+ const std::atomic<bool>* owner_=nullptr;const std::atomic<bool>* local_=nullptr;+ bool network_=false;std::atomic<int64_t> deadline_{0};+};+inline void networkMediaOptions(AVDictionary** options){+ static std::once_flag initialized;std::call_once(initialized,[]{avformat_network_init();});+ av_dict_set(options,"rw_timeout","5000000",0);av_dict_set(options,"timeout","5000000",0);+ av_dict_set(options,"rtsp_transport","tcp",0);+}+}diff --git a/include/veyra/sink/WasapiAudioSink.h b/include/veyra/sink/WasapiAudioSink.hindex 8917439b..be62df7e 100644--- a/include/veyra/sink/WasapiAudioSink.h+++ b/include/veyra/sink/WasapiAudioSink.h@@ -1,4 +1,5 @@#pragma once+#include "veyra/media/NetworkInput.h"// AudioPipeline: FFmpeg audio demux/decode + watermarked bounded ring// (low 250ms / prefill 500ms / high 1000ms, 2s hard bound).@@ -71,7 +72,7 @@ public:AudioPipeline();~AudioPipeline();- bool open(const std::wstring& path);+ bool open(const std::wstring& path,const std::atomic<bool>* cancelled=nullptr);const std::vector<media::AudioTrack>& tracks() const { return tracks_; }int selectedTrack() const { return streamIndex_; }// Owner thread only, after stopThread(). Failure preserves the old decoder.@@ -159,6 +160,7 @@ private:AudioFormat pcmFormat_;std::vector<media::AudioTrack> tracks_;AVFormatContext* fmt_ = nullptr;+ media::InputInterrupt inputInterrupt_;AVCodecContext* codecCtx_ = nullptr;AVStream* stream_ = nullptr;AVPacket* packet_ = nullptr;diff --git a/include/veyra/source/IFrameSource.h b/include/veyra/source/IFrameSource.hindex 5adc0417..a3426537 100644--- a/include/veyra/source/IFrameSource.h+++ b/include/veyra/source/IFrameSource.h@@ -6,6 +6,7 @@// linear RGBA16F working texture (Product Spec 7).#include <cstdint>#include <string>+#include <atomic>#include "veyra/pipeline/FramePacket.h"#include "veyra/source/DolbyVision.h"@@ -28,6 +29,8 @@ struct SourceOpenDesc {// D3D11 device on the same adapter so decoded surfaces can be shared.uint64_t d3d12AdapterLuid = 0;bool legacyCaptureRgbForDiagnostic = false; // explicit A/B only; never set by the player+ const std::atomic<bool>* cancelled = nullptr;+ bool deinterlace = false; // playback opt-in; unchanged default for offline consumers};struct SourceInfo {@@ -47,6 +50,8 @@ struct SourceInfo {int nominalRateNum = 0, nominalRateDen = 0; // candidate, not proof of CFRdouble timestampQuantum = 0.0;bool hardwareDecodeActive = false;+ bool deinterlaced = false;+ std::string deinterlacePath;// Which decode path actually produced the frames: "d3d12va", "d3d11va" or// "software". Descriptive only; the UI/telemetry must not claim a path the// session is not using.diff --git a/include/veyra/source/MediaFileSource.h b/include/veyra/source/MediaFileSource.hindex d76c0734..b6d8c14c 100644--- a/include/veyra/source/MediaFileSource.h+++ b/include/veyra/source/MediaFileSource.h@@ -12,6 +12,7 @@#include "veyra/media/FFmpegDemuxer.h"#include "veyra/media/FFmpegVideoDecoder.h"+#include "veyra/media/FFmpegDeinterlacer.h"#include "veyra/source/IFrameSource.h"namespace veyra::source {@@ -41,6 +42,8 @@ private:media::FFmpegDemuxer demuxer_;media::FFmpegVideoDecoder decoder_;+ media::FFmpegDeinterlacer deinterlacer_;+ bool deinterlaceEnabled_=true,filterDraining_=false;SourceInfo info_{};uint64_t sequence_ = 0;uint64_t epoch_ = 1;@@ -55,6 +58,7 @@ private:std::wstring path_;bool preferHardwareDecode_ = false;bool requireHardwareDecode_ = false; // "强制硬解": never fall back to software+ const std::atomic<bool>* cancelled_ = nullptr;};} // namespace veyra::sourcediff --git a/include/veyra/ui/QmlPlayerBridge.h b/include/veyra/ui/QmlPlayerBridge.hindex d7acc739..eda5caf7 100644--- a/include/veyra/ui/QmlPlayerBridge.h+++ b/include/veyra/ui/QmlPlayerBridge.h@@ -1107,6 +1107,8 @@ public:// Every one returns immediately; none touches the GPU or waits for the// engine.Q_INVOKABLE void openFileDialog();+ Q_INVOKABLE void openNetworkDialog();+ Q_INVOKABLE bool openNetworkAddress(const QString& address);Q_INVOKABLE void openPath(const QString& path);Q_INVOKABLE void openCaptureDialog();// Reopens the last capture session with the same device and format.diff --git a/qml/Veyra/CineBar.qml b/qml/Veyra/CineBar.qmlindex 2b5a2478..08c871cc 100644--- a/qml/Veyra/CineBar.qml+++ b/qml/Veyra/CineBar.qml@@ -470,6 +470,7 @@ Rectangle {title: qsTr("载入片源")items: [{ label: qsTr("打开视频"), note: qsTr("MP4 · MKV · 图片"), icon: "folder", act: "file" },+ { label: qsTr("播放地址…"), note: "HTTP · HTTPS · RTSP", icon: "cast", act: "network" },{ label: qsTr("采集卡"), note: qsTr("HDMI 采集设备"), icon: "video", act: "capture" },{ label: qsTr("PS5 串流"), note: qsTr("局域网串流"), icon: "gamepad", act: "ps5" },{ label: qsTr("PC 串流"), note: qsTr("Sunshine 主机"), icon: "cast", act: "moonlight" },@@ -479,6 +480,7 @@ Rectangle {onPicked: (i, o) => {switch (o.act) {case "file": veyra.openFileDialog(); break+ case "network": veyra.openNetworkDialog(); breakcase "capture": veyra.openCaptureDialog(); breakcase "ps5": veyra.openPs5Dialog(); breakcase "moonlight": veyra.openMoonlightDialog(); breakdiff --git a/qml/Veyra/DialogHost.qml b/qml/Veyra/DialogHost.qmlindex b5483691..99cb57e6 100644--- a/qml/Veyra/DialogHost.qml+++ b/qml/Veyra/DialogHost.qml@@ -210,6 +210,35 @@ Item {}}+ DLayer {+ id: networkDialog+ objectName: "network-dialog"+ key: "network"+ glyph: "cast"+ title: qsTr("播放地址")+ sub: qsTr("直接打开 HTTP、HTTPS 或 RTSP 视频流,例如 IPTV 或摄像机地址")+ dialogWidth: 640+ actions: [{label:qsTr("取消")},{label:qsTr("打开"),primary:true,icon:"play"}]+ onActionTriggered: label => {+ if(label!==qsTr("打开")){host.close();return}+ if(veyra.openNetworkAddress(networkAddress.text))host.close()+ }+ VTextField {+ id: networkAddress+ objectName: "network-address"+ Layout.fillWidth: true+ placeholder: "https://… / rtsp://…"+ }+ Text {+ Layout.fillWidth: true+ text: qsTr("需要直接媒体地址,普通网页或需要网页登录的页面不能直接播放。直播流通常无法拖动进度。")+ wrapMode: Text.Wrap+ color: Theme.t3+ font.family: Theme.fontUi+ font.pixelSize: 12+ }+ }+// --- 采集卡 -----------------------------------------------------------// The 1.4.4 capture panel, in the new design: device details and formats are// queried asynchronously, only an explicitly chosen audio input is opened,diff --git a/qml/Veyra/HomePage.qml b/qml/Veyra/HomePage.qmlindex 0c93fd37..9f5f339d 100644--- a/qml/Veyra/HomePage.qml+++ b/qml/Veyra/HomePage.qml@@ -212,6 +212,14 @@ VPage {}}+ VButton {+ objectName: "home-network"+ Layout.alignment: Qt.AlignHCenter+ text: qsTr("播放地址…")+ iconName: "cast"+ onClicked: veyra.openNetworkDialog()+ }+// .resume: 692 wide, an accent-tinted gradient plate, shown only when a// capture session was actually used before. Nothing invented: the text is// the recorded session, and the row is absent when there is none.diff --git a/qml/Veyra/Main.qml b/qml/Veyra/Main.qmlindex 23b89a92..67b5b1ad 100644--- a/qml/Veyra/Main.qml+++ b/qml/Veyra/Main.qml@@ -695,6 +695,7 @@ Window {Shortcut { sequence: "Up"; onActivated: veyra.volume = Math.min(1, veyra.volume + 0.05) }Shortcut { sequence: "Down"; onActivated: veyra.volume = Math.max(0, veyra.volume - 0.05) }Shortcut { sequence: "Ctrl+O"; onActivated: veyra.openFileDialog() }+ Shortcut { sequence: "Ctrl+U"; onActivated: veyra.openNetworkDialog() }Shortcut { sequence: "Ctrl+E"; onActivated: root.page = "exp" }Shortcut {sequence: veyra.shortcuts.lock@@ -789,7 +790,7 @@ Window {function onOverlayRestartSuggested(kind) { overlayRestart.kind = kind; overlayRestart.open() }function onNavigate(p) {// A dialog key opens the dialog; anything else is a page.- if (p === "capture" || p === "ps5" || p === "moonlight" || p === "xbox" || p === "screen"+ if (p === "network" || p === "capture" || p === "ps5" || p === "moonlight" || p === "xbox" || p === "screen"|| p === "subtitle" || p === "audio" || p === "save" || p === "manage") {dialogs.open(p)returndiff --git a/qml/Veyra/MinimalPage.qml b/qml/Veyra/MinimalPage.qmlindex 50ac5ad6..2eccff24 100644--- a/qml/Veyra/MinimalPage.qml+++ b/qml/Veyra/MinimalPage.qml@@ -116,6 +116,7 @@ VPage {objectName: "min-source-menu"title: qsTr("片源")items: [{ label: qsTr("打开文件…"), icon: "folder", act: "file" },+ { label: qsTr("播放地址…"), icon: "cast", act: "network" },{ label: qsTr("PS5 串流…"), icon: "gamepad", act: "ps5" },{ label: qsTr("PC 串流…"), icon: "cast", act: "moonlight" },{ label: qsTr("Xbox 串流…"), icon: "gamepad", act: "xbox" },@@ -124,6 +125,7 @@ VPage {{ label: qsTr("采集卡设置…"), icon: "settings", act: "capture" }]onPicked: (i, o) => {if (o.act === "file") veyra.openFileDialog()+ else if (o.act === "network") veyra.openNetworkDialog()else if (o.act === "ps5") veyra.openPs5Dialog()else if (o.act === "moonlight") veyra.openMoonlightDialog()else if (o.act === "xbox") veyra.openXboxDialog()diff --git a/qml/Veyra/NodePage.qml b/qml/Veyra/NodePage.qmlindex d5c9c54a..6086ec45 100644--- a/qml/Veyra/NodePage.qml+++ b/qml/Veyra/NodePage.qml@@ -1742,6 +1742,7 @@ VPage {items: (veyra.sourceTitle.length > 0? [{ label: veyra.sourceTitle, note: veyra.sourceFormatText, checked: true, icon: "video", act: "" }] : []).concat([{ label: qsTr("打开文件…"), icon: "folder", act: "file" },+ { label: qsTr("播放地址…"), icon: "cast", act: "network" },{ label: qsTr("PS5 串流…"), icon: "gamepad", act: "ps5" },{ label: qsTr("PC 串流…"), icon: "cast", act: "moonlight" },{ label: qsTr("Xbox 串流…"), icon: "gamepad", act: "xbox" },@@ -1750,6 +1751,7 @@ VPage {{ label: qsTr("采集卡设置…"), icon: "settings", act: "capture" }])onPicked: (i, o) => {if (o.act === "file") veyra.openFileDialog()+ else if (o.act === "network") veyra.openNetworkDialog()else if (o.act === "ps5") veyra.openPs5Dialog()else if (o.act === "moonlight") veyra.openMoonlightDialog()else if (o.act === "xbox") veyra.openXboxDialog()diff --git a/qml/Veyra/ProPage.qml b/qml/Veyra/ProPage.qmlindex 11837ccf..23033bf0 100644--- a/qml/Veyra/ProPage.qml+++ b/qml/Veyra/ProPage.qml@@ -282,9 +282,9 @@ VPage {}// The status light: 1.4.4's 当前状态 (正常 / 补帧调度降档 / 输出未达标 /// 输入帧率不足 …) as a glowing strip with the detail beside it.- component StatusLight: RowLayout {+ component StatusLight: ColumnLayout {id: light- spacing: 8+ spacing: 6readonly property color tone: veyra.runStatusLevel === "ok" ? Theme.ok: veyra.runStatusLevel === "warn" ? "#F2B941": veyra.runStatusLevel === "err" ? Theme.err : Qt.rgba(1, 1, 1, 0.3)@@ -313,8 +313,7 @@ VPage {}Text {objectName: "run-status"- Layout.maximumWidth: Math.max(0, light.width - 40)- Layout.preferredWidth: Math.min(implicitWidth, light.width * 0.75)+ Layout.fillWidth: truetext: veyra.runStatus + (veyra.runStatusDetail.length > 0 ? " · " + veyra.runStatusDetail : "")color: light.tonefont.family: Theme.fontUi@@ -322,8 +321,6 @@ VPage {font.weight: Font.MediumhorizontalAlignment: Text.AlignRightwrapMode: Text.Wrap- maximumLineCount: 2- elide: Text.ElideRightHoverHandler { id: statusHover }ToolTip.visible: statusHover.hoveredToolTip.delay: 400@@ -342,8 +339,6 @@ VPage {font.family: Theme.fontUifont.pixelSize: 11wrapMode: Text.Wrap- maximumLineCount: 3- elide: Text.ElideRightHoverHandler { id: optionsHover }ToolTip.visible: optionsHover.hoveredToolTip.delay: 400@@ -2260,6 +2255,7 @@ VPage {? [{ label: (veyra.isCapture ? qsTr("采集卡 · ") : "") + veyra.sourceName, note: veyra.sourceSummary,checked: true, icon: "video", act: "" }] : []).concat([{ label: qsTr("打开文件…"), icon: "folder", act: "file" },+ { label: qsTr("播放地址…"), icon: "cast", act: "network" },{ label: qsTr("PS5 串流…"), icon: "gamepad", act: "ps5" },{ label: qsTr("PC 串流…"), icon: "cast", act: "moonlight" },{ label: qsTr("Xbox 串流…"), icon: "gamepad", act: "xbox" },@@ -2268,6 +2264,7 @@ VPage {{ label: qsTr("采集卡设置…"), icon: "settings", act: "capture" }])onPicked: (i, o) => {if (o.act === "file") veyra.openFileDialog()+ else if (o.act === "network") veyra.openNetworkDialog()else if (o.act === "ps5") veyra.openPs5Dialog()else if (o.act === "moonlight") veyra.openMoonlightDialog()else if (o.act === "xbox") veyra.openXboxDialog()diff --git a/qml/Veyra/SettingsPage.qml b/qml/Veyra/SettingsPage.qmlindex ecc0f715..f92339de 100644--- a/qml/Veyra/SettingsPage.qml+++ b/qml/Veyra/SettingsPage.qml@@ -356,6 +356,11 @@ VPage {hint: qsTr("HDR10 默认;补帧固定 HDR10,需要 Windows HDR 开启")VSeg { options: [{id:"0",label:"HDR10"},{id:"1",label:qsTr("scRGB 浮点")}]; current: String(veyra.hdrOutputMode); onPicked: id => veyra.hdrOutputMode = Number(id) }}+ VRow {+ label: qsTr("自动去隔行")+ hint: qsTr("只处理标记为隔行的视频,优先使用 GPU;软解使用兼容算法。下次打开视频生效。")+ VSwitch { checked: veyra.preferences.deinterlace !== false; onToggled: checked => veyra.setPreference("deinterlace",checked) }+ }// HDR 亮度曲线: static, so the highlights are protected.// One-click presets (same ids as the list page).Flow {diff --git a/scripts/ffmpeg/build-deinterlace-module.py b/scripts/ffmpeg/build-deinterlace-module.pynew file mode 100644index 00000000..ebbc0e57--- /dev/null+++ b/scripts/ffmpeg/build-deinterlace-module.py@@ -0,0 +1,100 @@+from pathlib import Path+import hashlib,json,os,subprocess,time,urllib.request,zipfile++import argparse+parser=argparse.ArgumentParser();parser.add_argument('--task',default='issues41-45-20261016');args=parser.parse_args()+base=Path('E:/项目/Veyra');task=args.task+root=Path(__file__).resolve().parents[2]+work=base/'build'/task/'ffmpeg-filter';logs=base/'logs'/task/'ffmpeg-filter'+tmp=base/'tmp'/task/'filter-build';prefix=base/'deps'/('ffmpeg-filter-'+task)+for path in [work,logs,tmp,prefix]:path.mkdir(parents=True,exist_ok=True)++def sha(path):+ with path.open('rb') as stream:return hashlib.file_digest(stream,'sha256').hexdigest()++archive=base/'downloads'/'FFmpeg-n9.0.1-issues41-45-20261016.zip'+if not archive.exists():+ with urllib.request.urlopen('https://codeload.github.com/FFmpeg/FFmpeg/zip/refs/tags/n9.0.1',timeout=30) as response:+ archive.write_bytes(response.read())+src=work/'FFmpeg-n9.0.1'+if not src.exists():+ with zipfile.ZipFile(archive) as source:+ for item in source.infolist():+ assert (work/item.filename).resolve().is_relative_to(work.resolve())+ source.extractall(work)+tag=json.loads(urllib.request.urlopen('https://api.github.com/repos/FFmpeg/FFmpeg/git/ref/tags/n9.0.1',timeout=20).read())+obj=tag['object']+if obj['type']=='tag':obj=json.loads(urllib.request.urlopen(obj['url'],timeout=20).read())['object']+assert obj['type']=='commit' and obj['sha']=='bf1b838f2ab88b4f8fd83443325c782ea0e0f7fa'+assert sha(archive)=='d16837ddbb0963753aa2739971a09b07fe14fe855a6e84f253f851127f99c746'+patch=root/'scripts/ffmpeg/deinterlace-d3d12-async.patch'+check=subprocess.run(['git','apply','--check',str(patch)],cwd=src,stdout=subprocess.PIPE,stderr=subprocess.PIPE)+if check.returncode==0:subprocess.run(['git','apply',str(patch)],cwd=src,check=True)+else:subprocess.run(['git','apply','--reverse','--check',str(patch)],cwd=src,check=True)+print('source',obj['sha'],'archive',sha(archive),flush=True)+configure_source=src/'configure'+configuration=configure_source.read_text(encoding='utf8')+# This host has the Chinese-only MSVC banner. Detection must not require+# 'Microsoft' at column 0; retain the actual compiler, flags and ABI.+configuration=configuration.replace('grep -q ^Microsoft','grep -q Microsoft').replace('grep ^Microsoft','grep Microsoft')+configure_source.write_text(configuration,encoding='utf8')+env={key:value for key,value in os.environ.items() if not key.upper().startswith(('VEYRA_','QT_','QML_','QSG_'))}+env.update(TEMP=str(tmp),TMP=str(tmp),VSLANG='1033',PYTHONDONTWRITEBYTECODE='1')+setup=subprocess.run(['cmd.exe','/u','/d','/c',r'call C:\PROGRA~2\MICROS~3\2022\BUILDT~1\VC\Auxiliary\Build\vcvars64.bat >nul && set'],env=env,stdout=subprocess.PIPE,stderr=subprocess.DEVNULL,check=True)+for line in setup.stdout.decode('utf-16-le').splitlines():+ if '=' in line:+ key,value=line.split('=',1)+ if key and not key.startswith('='):env[key]=value+msys=Path('C:/veyra-deps/vcpkg/downloads/tools/msys2/0fcfdbb60b602f3c')+env={key.upper():value for key,value in env.items()}+env['VSLANG']='1033'+bash=msys/'usr/bin/bash.exe';make=msys/'usr/bin/make.exe'+assert bash.exists() and make.exists()+env['PATH']=str(Path(env['VCTOOLSINSTALLDIR'])/'bin/Hostx64/x64')+';'+str(msys/'usr/bin')+';'+env['PATH']+env.update(MSYS2_PATH_TYPE='inherit',MSYS_NO_PATHCONV='1',TEMP=str(tmp),TMP=str(tmp))+flags=['--toolchain=msvc','--arch=x86_64','--target-os=win32','--disable-doc','--disable-programs',+ '--disable-everything','--disable-autodetect','--disable-avcodec','--disable-avformat','--disable-avdevice',+ '--disable-swscale','--disable-swresample','--enable-avfilter','--enable-filter=bwdif,deinterlace_d3d12',+ '--enable-d3d12va','--enable-d3d11va','--enable-shared','--disable-static','--disable-x86asm',+ '--enable-w32threads','--cc=cl.exe','--cxx=cl.exe','--ld=link.exe',+ '--ar='+str(msys/'usr/share/automake-1.18/ar-lib')+' lib.exe','--ranlib=:',+ '--extra-cflags=-MD','--extra-cxxflags=-MD','--prefix='+str(prefix)]+commands=[('configure',[str(bash),'./configure',*flags]),('compile',[str(make),'-j8','libavfilter/avfilter-12.dll'])]+start=time.monotonic()+for name,command in commands:+ if (logs/(name+'.log')).exists():+ import shutil+ shutil.copy2(logs/(name+'.log'),logs/(name+'-previous-'+str(time.time_ns())+'.log'))+ if name=='configure' and (src/'ffbuild/config.log').exists():+ import shutil+ shutil.copy2(src/'ffbuild/config.log',logs/('config-previous-'+str(time.time_ns())+'.log'))+ with (logs/(name+'.log')).open('wb') as stream:+ result=subprocess.run(command,cwd=src,env=env,stdout=stream,stderr=subprocess.STDOUT,timeout=max(1,880-(time.monotonic()-start)))+ print(name,result.returncode,str(logs/(name+'.log')),flush=True)+ if result.returncode:+ print((logs/(name+'.log')).read_text(encoding='utf8',errors='replace')[-6500:]);raise SystemExit(result.returncode)+ if name=='configure':+ import re+ generated=src/'config.h';contents=generated.read_text(encoding='utf8')+ contents=re.sub(r'^#define CC_IDENT .*$', '#define CC_IDENT "Microsoft MSVC 19.44 (localized host)"',contents,flags=re.M)+ generated.write_text(contents,encoding='utf8')+dll=src/'libavfilter/avfilter-12.dll';assert dll.exists()+# Add one LGPL filter DLL and its public headers to a new dependency prefix.+# Existing approved codec/demux/util DLLs are reused byte-for-byte, never replaced.+old=base/'deps/ffmpeg-subtitle-formats-20261009/installed'+for path in old.rglob('*'):+ if path.is_file():+ dest=prefix/path.relative_to(old);dest.parent.mkdir(parents=True,exist_ok=True)+ if not dest.exists():os.link(path,dest)+(prefix/'bin').mkdir(exist_ok=True)+import shutil+shutil.copy2(dll,prefix/'bin/avfilter-12.dll')+headers=prefix/'include/libavfilter';headers.mkdir(parents=True,exist_ok=True)+for path in (src/'libavfilter').glob('*.h'):shutil.copy2(path,headers/path.name)+receipt=dict(passed=True,tag='n9.0.1',commit=obj['sha'],archive=str(archive),archiveSha256=sha(archive),+ source=str(src),patch=str(patch),patchSha256=sha(patch),commands=commands,filterDll=str(prefix/'bin/avfilter-12.dll'),filterSha256=sha(dll),+ existingRuntimeFilesPreserved=all(sha(path)==sha(prefix/path.relative_to(old)) for path in old.rglob('*') if path.is_file()),+ seconds=time.monotonic()-start,license='LGPL-2.1-or-later')+(logs/'receipt.json').write_text(json.dumps(receipt,ensure_ascii=False,indent=2),encoding='utf8')+assert receipt['existingRuntimeFilesPreserved']+print('PASS',json.dumps(receipt,ensure_ascii=False),flush=True)diff --git a/scripts/ffmpeg/deinterlace-d3d12-async.patch b/scripts/ffmpeg/deinterlace-d3d12-async.patchnew file mode 100644index 00000000..3b04132b--- /dev/null+++ b/scripts/ffmpeg/deinterlace-d3d12-async.patch@@ -0,0 +1,183 @@+--- a/libavfilter/vf_deinterlace_d3d12.c++++ b/libavfilter/vf_deinterlace_d3d12.c+@@ -57,7 +57,11 @@+ ID3D12VideoProcessor *video_processor;+ ID3D12CommandQueue *command_queue;+ ID3D12VideoProcessCommandList *command_list;+- ID3D12CommandAllocator *command_allocator;++ ID3D12CommandAllocator *command_allocator; /* borrowed current slot */++ ID3D12VideoProcessCommandList *command_lists[8];++ ID3D12CommandAllocator *command_allocators[8];++ UINT64 slot_fences[8];++ AVFrame *slot_inputs[8][MAX_REFERENCES + 1];++ /* Synchronization */+ ID3D12Fence *fence;+@@ -120,7 +124,7 @@+ if (completed < fence_value) {+ hr = ID3D12Fence_SetEventOnCompletion(s->fence, fence_value, s->fence_event);+ if (SUCCEEDED(hr)) {+- WaitForSingleObject(s->fence_event, INFINITE);++ WaitForSingleObject(s->fence_event, 5000);+ }+ }+ }+@@ -136,15 +140,17 @@+ s->fence = NULL;+ }++- if (s->command_list) {+- ID3D12VideoProcessCommandList_Release(s->command_list);+- s->command_list = NULL;+- }+-+- if (s->command_allocator) {+- ID3D12CommandAllocator_Release(s->command_allocator);+- s->command_allocator = NULL;+- }++ for (int slot = 0; slot < 8; ++slot) {++ for (int ref = 0; ref < MAX_REFERENCES + 1; ++ref)++ av_frame_free(&s->slot_inputs[slot][ref]);++ if (s->command_lists[slot]) ID3D12VideoProcessCommandList_Release(s->command_lists[slot]);++ if (s->command_allocators[slot]) ID3D12CommandAllocator_Release(s->command_allocators[slot]);++ s->command_lists[slot] = NULL;++ s->command_allocators[slot] = NULL;++ s->slot_fences[slot] = 0;++ }++ s->command_list = NULL;++ s->command_allocator = NULL;++ if (s->video_processor) {+ ID3D12VideoProcessor_Release(s->video_processor);+@@ -204,7 +210,9 @@+ {+ AVRational framerate = {0, 0};++- if (in->duration > 0 && inlink->time_base.num > 0 && inlink->time_base.den > 0) {++ if (ff_filter_link(inlink)->frame_rate.num > 0 && ff_filter_link(inlink)->frame_rate.den > 0) {++ framerate = ff_filter_link(inlink)->frame_rate;++ } else if (in->duration > 0 && inlink->time_base.num > 0 && inlink->time_base.den > 0) {+ av_reduce(&framerate.num, &framerate.den,+ inlink->time_base.den, in->duration * inlink->time_base.num,+ INT_MAX);+@@ -458,11 +466,12 @@+ return AVERROR_EXTERNAL;+ }+++ for (int slot = 0; slot < 8; ++slot) {+ hr = ID3D12Device_CreateCommandAllocator(+ s->device,+ D3D12_COMMAND_LIST_TYPE_VIDEO_PROCESS,+ &IID_ID3D12CommandAllocator,+- (void **)&s->command_allocator++ (void **)&s->command_allocators[slot]+ );++ if (FAILED(hr)) {+@@ -474,10 +483,10 @@+ s->device,+ 0,+ D3D12_COMMAND_LIST_TYPE_VIDEO_PROCESS,+- s->command_allocator,++ s->command_allocators[slot],+ NULL,+ &IID_ID3D12VideoProcessCommandList,+- (void **)&s->command_list++ (void **)&s->command_lists[slot]+ );++ if (FAILED(hr)) {+@@ -485,7 +494,8 @@+ return AVERROR_EXTERNAL;+ }++- ID3D12VideoProcessCommandList_Close(s->command_list);++ ID3D12VideoProcessCommandList_Close(s->command_lists[slot]);++ }++ hr = ID3D12Device_CreateFence(s->device, 0, D3D12_FENCE_FLAG_NONE, &IID_ID3D12Fence, (void **)&s->fence);+ if (FAILED(hr)) {+@@ -536,6 +546,31 @@+ HRESULT hr;++ AVD3D12VAFrame *in_d3d12_frame = (AVD3D12VAFrame *)input_frame->data[0];++++ /* Veyra: only reuse an allocator after its submission completes. Keep++ * decoder/reference frames alive until that same fence. No per-pass wait. */++ const unsigned slot = (unsigned)((s->fence_value - 1) % 8);++ if (s->slot_fences[slot] && ID3D12Fence_GetCompletedValue(s->fence) < s->slot_fences[slot]) {++ hr = ID3D12Fence_SetEventOnCompletion(s->fence, s->slot_fences[slot], s->fence_event);++ if (FAILED(hr) || WaitForSingleObject(s->fence_event, 5000) != WAIT_OBJECT_0)++ return AVERROR_EXTERNAL;++ }++ for (int ref = 0; ref < MAX_REFERENCES + 1; ++ref)++ av_frame_free(&s->slot_inputs[slot][ref]);++ s->slot_inputs[slot][0] = av_frame_clone(input_frame);++ if (!s->slot_inputs[slot][0]) return AVERROR(ENOMEM);++ if (queue_idx >= 0) {++ int count = 1;++ for (int q = FFMAX(0, queue_idx - s->num_past_frames);++ q <= FFMIN(s->queue_count - 1, queue_idx + s->num_future_frames); ++q) {++ if (q == queue_idx || !s->frame_queue[q]) continue;++ if (count >= MAX_REFERENCES + 1) return AVERROR(EINVAL);++ s->slot_inputs[slot][count] = av_frame_clone(s->frame_queue[q]);++ if (!s->slot_inputs[slot][count++]) return AVERROR(ENOMEM);++ }++ }++ s->command_allocator = s->command_allocators[slot];++ s->command_list = s->command_lists[slot];++ out = av_frame_alloc();+ if (!out) {+@@ -738,9 +773,12 @@+ goto fail;+ }++- out_d3d12_frame->sync_ctx.fence = s->fence;++ s->slot_fences[slot] = s->fence_value;++ /* Retain the output pool's own fence. Replacing it leaked one fence++ * reference on every field and broke the pool's synchronization contract. */++ hr = ID3D12CommandQueue_Signal(s->command_queue, out_d3d12_frame->sync_ctx.fence, s->fence_value);++ if (FAILED(hr)) { ret = AVERROR_EXTERNAL; goto fail; }+ out_d3d12_frame->sync_ctx.fence_value = s->fence_value;+- ID3D12Fence_AddRef(s->fence);++ s->fence_value++;++@@ -750,23 +788,22 @@+ goto fail;+ }++- out->width = s->width;+- out->height = s->height;++ out->width = input_frame->width;++ out->height = input_frame->height;+ out->format = AV_PIX_FMT_D3D12;+ out->flags &= ~AV_FRAME_FLAG_INTERLACED;++- /* Calculate output PTS for field rate output */+- if (s->mode && queue_idx >= 0) {+- AVFrame *next_frame = (queue_idx + 1 < s->queue_count) ?+- s->frame_queue[queue_idx + 1] : NULL;+-+- if (field == 0) {+- out->pts = 2 * input_frame->pts;+- } else if (s->eof || !next_frame) {+- out->pts = 3 * input_frame->pts - s->prev_pts;+- } else {+- out->pts = input_frame->pts + next_frame->pts;+- }++ /* Field time base is half the input base, including short-stream EOF.++ * Never extrapolate the first frame against an uninitialized prev_pts. */++ if (s->mode && input_frame->pts != AV_NOPTS_VALUE) {++ AVFrame *next_frame = queue_idx >= 0 && queue_idx + 1 < s->queue_count ? s->frame_queue[queue_idx + 1] : NULL;++ int64_t step = input_frame->duration;++ if (next_frame && next_frame->pts != AV_NOPTS_VALUE && next_frame->pts > input_frame->pts)++ step = next_frame->pts - input_frame->pts;++ if (step <= 0) step = av_rescale_q(1, av_inv_q(s->input_framerate), ctx->inputs[0]->time_base);++ step = FFMAX(step, 1);++ out->pts = 2 * input_frame->pts + (field ? step : 0);++ out->duration = step * ((input_frame->flags & AV_FRAME_FLAG_INTERLACED) ? 1 : 2);+ }++ av_log(ctx, AV_LOG_DEBUG, "Deinterlace output: %dx%d, pts=%"PRId64", field=%d\n",diff --git a/src/engine/EngineController.cpp b/src/engine/EngineController.cppindex 384bf680..bd652908 100644--- a/src/engine/EngineController.cpp+++ b/src/engine/EngineController.cpp@@ -554,6 +554,8 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,ssnapshot_.sourceRotationDegrees=0;}}else{source::SourceOpenDesc od;od.path=path;+ od.cancelled=&stop_;+ od.deinterlace=options.deinterlace;// Files use the same shared D3D12 device as the graph-> Capture// uses it for the compressed-payload decoder (H.264/HEVC/AV1/// VP9 through D3D12VA; MJPEG stays on the software path inside@@ -671,7 +673,8 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,sif(posterSource&&makePosterFrame(posterSource,320,180,poster,pw,ph)){snapshot_.posterRgba=std::move(poster);snapshot_.posterWidth=pw;snapshot_.posterHeight=ph;}else{snapshot_.posterRgba.clear();snapshot_.posterWidth=snapshot_.posterHeight=0;}}- {std::lock_guard lock(mutex_);snapshot_.sourceNotice=activeSource->info().dolbyVision.description();}+ {std::lock_guard lock(mutex_);snapshot_.sourceNotice=activeSource->info().dolbyVision.description();+ const auto& si=activeSource->info();if(si.deinterlaced)snapshot_.sourceNotice+=std::format(L"{}去隔行:{} · {:.3f}i → {:.3f}p",snapshot_.sourceNotice.empty()?L"":L" · ",si.deinterlacePath=="d3d12-video-processor"?L"GPU":L"兼容软解",si.averageFps,si.averageFps);}}if(!pipeline::Extent{width,height}.valid()){status(L"图像尺寸超出单张GPU纹理能力,需要分块处理",true);break;}HdrDisplayState displayHdrState;@@ -904,7 +907,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,suint64_t seekDecoded=0;bool fileAwaitingVideo=true,fileAudioAlignPending=true,fileInputEnded=false;double lastFilePresentedMs=0,lastFilePresentLateness=0;TimingWindow presentEntryDeviation,presentReturnDeviation;- if(!isImage&&!isCapture&&audioPipe.open(path)){+ if(!isImage&&!isCapture&&audioPipe.open(path,&stop_)){{std::lock_guard lock(mutex_);snapshot_.audioTracks=audioPipe.tracks();snapshot_.selectedAudioTrack=audioPipe.selectedTrack();}audioPipe.holdForVideo();audioPipe.startThread(&audio,true);audioStarted=true;std::lock_guard lock(mutex_);snapshot_.audioAvailable=true;diff --git a/src/engine/VideoPresenter.cpp b/src/engine/VideoPresenter.cppindex 44a8ae43..7231de15 100644--- a/src/engine/VideoPresenter.cpp+++ b/src/engine/VideoPresenter.cpp@@ -478,7 +478,7 @@ PresentationSettings VideoPresenter::configurePresentation(gfx::D3D12DeviceConteeffective.outputRate=OutputRateMode::Off;capNotice=L" · 此补帧提供方暂不支持独立输出限帧;已保留设置";}- // 可变刷新: with VRR possible on this monitor, Automatic presents like+ // 可变刷新: when the applied monitor mode can request VRR, Automatic presents like// explicit Vsync - the G-SYNC/FreeSync + V-SYNC combination. Inside the// VRR range the panel starts a refresh when the frame arrives, so the// VSync wait is about zero and nothing tears; above the range thediff --git a/src/media/FFmpegDeinterlacer.cpp b/src/media/FFmpegDeinterlacer.cppnew file mode 100644index 00000000..d056e5a0--- /dev/null+++ b/src/media/FFmpegDeinterlacer.cpp@@ -0,0 +1,179 @@+#include "veyra/media/FFmpegDeinterlacer.h"+#include "veyra/media/FFmpegVideoDecoder.h"+#include "veyra/Log.h"+#include <windows.h>+#include <filesystem>+#include <format>+#include <algorithm>+extern "C" {+#include <libavutil/frame.h>+#include <libavutil/error.h>+}+#if __has_include(<libavfilter/avfilter.h>)+#define VEYRA_HAS_AVFILTER_HEADERS 1+extern "C" {+#include <libavfilter/avfilter.h>+#include <libavfilter/buffersrc.h>+#include <libavfilter/buffersink.h>+#include <libavutil/hwcontext.h>+#include <libavutil/hwcontext_d3d12va.h>+}+#endif++namespace veyra::media {+#ifdef VEYRA_HAS_AVFILTER_HEADERS+namespace {+struct FilterApi {+#define FILTER_API(name) decltype(&::name) name=nullptr+ FILTER_API(avfilter_graph_alloc);FILTER_API(avfilter_graph_free);+ FILTER_API(avfilter_get_by_name);FILTER_API(avfilter_graph_create_filter);+ FILTER_API(avfilter_link);FILTER_API(avfilter_graph_config);+ FILTER_API(av_buffersrc_add_frame_flags);FILTER_API(av_buffersink_get_frame);+ FILTER_API(av_buffersink_get_time_base);FILTER_API(av_buffersrc_parameters_alloc);+ FILTER_API(av_buffersrc_parameters_set);+#undef FILTER_API+ bool ready=false;+ FilterApi(){+ wchar_t executable[32768]{};+ if(!GetModuleFileNameW(nullptr,executable,32768))return;+ const auto path=std::filesystem::path(executable).parent_path()/L"avfilter-12.dll";+ auto module=LoadLibraryExW(path.c_str(),nullptr,LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR|LOAD_LIBRARY_SEARCH_SYSTEM32);+ if(!module){log::warn("deinterlace",std::format("optional avfilter module unavailable Win32={}",GetLastError()));return;}+#define FILTER_API(name) name=reinterpret_cast<decltype(name)>(GetProcAddress(module,#name));if(!name)return+ FILTER_API(avfilter_graph_alloc);FILTER_API(avfilter_graph_free);+ FILTER_API(avfilter_get_by_name);FILTER_API(avfilter_graph_create_filter);+ FILTER_API(avfilter_link);FILTER_API(avfilter_graph_config);+ FILTER_API(av_buffersrc_add_frame_flags);FILTER_API(av_buffersink_get_frame);+ FILTER_API(av_buffersink_get_time_base);FILTER_API(av_buffersrc_parameters_alloc);+ FILTER_API(av_buffersrc_parameters_set);+#undef FILTER_API+ ready=true; // Module intentionally retained while filters can exist.+ }+};+FilterApi& api(){static FilterApi value;return value;}+}+#endif+struct FFmpegDeinterlacer::Impl {+ std::string path;+ int num=0,den=0;+#ifdef VEYRA_HAS_AVFILTER_HEADERS+ AVFilterGraph* graph=nullptr;AVFilterContext* source=nullptr;AVFilterContext* sink=nullptr;+ AVFrame* output=nullptr;AVBufferRef* bridgeFrames=nullptr;+ AVFrame* input(const AVFrame* frame,const HardwareSurfaceView* surface){+ if(!frame)return nullptr;+ auto* copy=av_frame_clone(frame);+ if(copy&©->pts==AV_NOPTS_VALUE)copy->pts=copy->best_effort_timestamp!=AV_NOPTS_VALUE?copy->best_effort_timestamp:copy->pkt_dts;+ if(!copy||frame->format!=AV_PIX_FMT_D3D11)return copy;+ if(!surface||!surface->texture||!surface->waitFence){av_frame_free(©);return nullptr;}+ if(!bridgeFrames){+ auto* device=av_hwdevice_ctx_alloc(AV_HWDEVICE_TYPE_D3D12VA);+ if(!device){av_frame_free(©);return nullptr;}+ auto* context=reinterpret_cast<AVHWDeviceContext*>(device->data);+ auto* hardware=reinterpret_cast<AVD3D12VADeviceContext*>(context->hwctx);+ if(FAILED(surface->texture->GetDevice(IID_PPV_ARGS(&hardware->device)))||av_hwdevice_ctx_init(device)<0){+ av_buffer_unref(&device);av_frame_free(©);return nullptr;+ }+ bridgeFrames=av_hwframe_ctx_alloc(device);av_buffer_unref(&device);+ if(!bridgeFrames){av_frame_free(©);return nullptr;}+ auto* frames=reinterpret_cast<AVHWFramesContext*>(bridgeFrames->data);+ frames->format=AV_PIX_FMT_D3D12;+ frames->sw_format=surface->texture->GetDesc().Format==DXGI_FORMAT_P010?AV_PIX_FMT_P010:AV_PIX_FMT_NV12;+ frames->width=surface->textureWidth;frames->height=surface->textureHeight;+ if(av_hwframe_ctx_init(bridgeFrames)<0){av_buffer_unref(&bridgeFrames);av_frame_free(©);return nullptr;}+ }+ auto* descriptor=static_cast<AVD3D12VAFrame*>(av_mallocz(sizeof(AVD3D12VAFrame)));+ if(!descriptor){av_frame_free(©);return nullptr;}+ descriptor->texture=surface->texture;descriptor->texture->AddRef();+ descriptor->subresource_index=int(surface->subresourceIndex);+ descriptor->sync_ctx.fence=surface->waitFence;surface->waitFence->AddRef();+ descriptor->sync_ctx.fence_value=surface->waitValue;+ auto* reference=av_buffer_create(reinterpret_cast<uint8_t*>(descriptor),sizeof(*descriptor),+ [](void*,uint8_t* data){auto* d=reinterpret_cast<AVD3D12VAFrame*>(data);d->texture->Release();d->sync_ctx.fence->Release();av_free(d);},nullptr,0);+ if(!reference){descriptor->texture->Release();descriptor->sync_ctx.fence->Release();av_free(descriptor);av_frame_free(©);return nullptr;}+ // Keep the original D3D11 pool reference in buf[0]. This extra buffer+ // owns only the imported descriptor, texture and interop fence.+ int slot=0;while(slot<AV_NUM_DATA_POINTERS&©->buf[slot])++slot;+ if(slot==AV_NUM_DATA_POINTERS){av_buffer_unref(&reference);av_frame_free(©);return nullptr;}+ copy->buf[slot]=reference;copy->data[0]=reference->data;copy->data[1]=nullptr;copy->format=AV_PIX_FMT_D3D12;+ av_buffer_unref(©->hw_frames_ctx);copy->hw_frames_ctx=av_buffer_ref(bridgeFrames);+ return copy;+ }+#endif+};+FFmpegDeinterlacer::FFmpegDeinterlacer():impl_(std::make_unique<Impl>()){}+FFmpegDeinterlacer::~FFmpegDeinterlacer(){close();}+bool FFmpegDeinterlacer::open(const AVFrame* frame,const HardwareSurfaceView* surface,int num,int den,int fpsNum,int fpsDen){+ close();+#ifdef VEYRA_HAS_AVFILTER_HEADERS+ auto& a=api();auto& i=*impl_;+ if(!a.ready||!frame||num<=0||den<=0)return false;+ auto* input=i.input(frame,surface);if(!input)return false;+ i.graph=a.avfilter_graph_alloc();+ if(!i.graph){av_frame_free(&input);return false;}+ const auto sar=input->sample_aspect_ratio.num>0&&input->sample_aspect_ratio.den>0?input->sample_aspect_ratio:AVRational{1,1};+ const auto args=std::format("video_size={}x{}:pix_fmt={}:time_base={}/{}:pixel_aspect={}/{}:frame_rate={}/{}",+ input->width,input->height,input->format,num,den,sar.num,sar.den,std::max(1,fpsNum),std::max(1,fpsDen));+ int result=a.avfilter_graph_create_filter(&i.source,a.avfilter_get_by_name("buffer"),"in",args.c_str(),nullptr,i.graph);+ if(result>=0&&input->hw_frames_ctx){+ auto* parameters=a.av_buffersrc_parameters_alloc();+ if(!parameters)result=AVERROR(ENOMEM);+ else{parameters->hw_frames_ctx=av_buffer_ref(input->hw_frames_ctx);result=a.av_buffersrc_parameters_set(i.source,parameters);av_buffer_unref(¶meters->hw_frames_ctx);av_free(parameters);}+ }+ const bool hardware=input->format==AV_PIX_FMT_D3D12;+ const char* name=hardware?"deinterlace_d3d12":"bwdif";+ const char* options=hardware?"method=default:mode=field:deint=interlaced":"mode=send_field:parity=auto:deint=interlaced";+ AVFilterContext* filter=nullptr;+ if(result>=0)result=a.avfilter_graph_create_filter(&filter,a.avfilter_get_by_name(name),"deinterlace",options,nullptr,i.graph);+ if(result>=0)result=a.avfilter_graph_create_filter(&i.sink,a.avfilter_get_by_name("buffersink"),"out",nullptr,nullptr,i.graph);+ if(result>=0)result=a.avfilter_link(i.source,0,filter,0);+ if(result>=0)result=a.avfilter_link(filter,0,i.sink,0);+ if(result>=0)result=a.avfilter_graph_config(i.graph,nullptr);+ av_frame_free(&input);+ if(result<0){log::error("deinterlace",std::format("filter configuration failed method={} code={}",name,result));close();return false;}+ i.output=av_frame_alloc();if(!i.output){close();return false;}+ const auto tb=a.av_buffersink_get_time_base(i.sink);i.num=tb.num;i.den=tb.den;i.path=hardware?"d3d12-video-processor":"bwdif-software";+ log::info("deinterlace",std::format("method={} fieldRate=true inputFps={}/{} outputTimeBase={}/{} gpuPixelReadbacks=0",i.path,fpsNum,fpsDen,i.num,i.den));+ return true;+#else+ return false;+#endif+}+int FFmpegDeinterlacer::push(const AVFrame* frame,const HardwareSurfaceView* surface){+#ifdef VEYRA_HAS_AVFILTER_HEADERS+ auto& i=*impl_;if(!i.source)return AVERROR(EINVAL);+ auto* input=i.input(frame,surface);if(frame&&!input)return AVERROR(ENOMEM);+ const int result=api().av_buffersrc_add_frame_flags(i.source,input,AV_BUFFERSRC_FLAG_KEEP_REF);+ av_frame_free(&input);return result;+#else+ return AVERROR(ENOSYS);+#endif+}+int FFmpegDeinterlacer::receive(const AVFrame** frame){+ *frame=nullptr;+#ifdef VEYRA_HAS_AVFILTER_HEADERS+ auto& i=*impl_;if(!i.output)return AVERROR(EINVAL);+ av_frame_unref(i.output);const int result=api().av_buffersink_get_frame(i.sink,i.output);+ if(result>=0)*frame=i.output;return result;+#else+ return AVERROR(ENOSYS);+#endif+}+int FFmpegDeinterlacer::timeBaseNum()const{return impl_->num;}+int FFmpegDeinterlacer::timeBaseDen()const{return impl_->den;}+bool FFmpegDeinterlacer::active()const{+#ifdef VEYRA_HAS_AVFILTER_HEADERS+ return impl_->output!=nullptr;+#else+ return false;+#endif+}+const std::string& FFmpegDeinterlacer::path()const{return impl_->path;}+void FFmpegDeinterlacer::close(){+#ifdef VEYRA_HAS_AVFILTER_HEADERS+ auto& i=*impl_;av_frame_free(&i.output);+ if(i.graph)api().avfilter_graph_free(&i.graph);+ av_buffer_unref(&i.bridgeFrames);i.source=i.sink=nullptr;+#endif+ impl_->path.clear();impl_->num=impl_->den=0;+}+}diff --git a/src/media/FFmpegDemuxer.cpp b/src/media/FFmpegDemuxer.cppindex cb5e51a7..8e2b6683 100644--- a/src/media/FFmpegDemuxer.cpp+++ b/src/media/FFmpegDemuxer.cpp@@ -22,7 +22,7 @@ FFmpegDemuxer::~FFmpegDemuxer()close();}-bool FFmpegDemuxer::open(const std::wstring& path)+bool FFmpegDemuxer::open(const std::wstring& path,const std::atomic<bool>* cancelled){if (context_ != nullptr) {close();@@ -35,8 +35,16 @@ bool FFmpegDemuxer::open(const std::wstring& path)utf8Path.resize(static_cast<size_t>(size));WideCharToMultiByte(CP_UTF8, 0, path.c_str(), static_cast<int>(path.size()), utf8Path.data(), size, nullptr, nullptr);}- AVFormatContext* raw = nullptr;- const int openResult = avformat_open_input(&raw, utf8Path.c_str(), nullptr, nullptr);+ AVFormatContext* raw = avformat_alloc_context();+ if(!raw)return false;+ const bool network=networkMediaInput(path);+ interrupt_.configure(network,cancelled);+ raw->interrupt_callback={InputInterrupt::callback,&interrupt_};+ AVDictionary* options=nullptr;+ if(network)networkMediaOptions(&options);+ interrupt_.arm();+ const int openResult = avformat_open_input(&raw, utf8Path.c_str(), nullptr, &options);+ av_dict_free(&options);if (openResult < 0) {char errorText[AV_ERROR_MAX_STRING_SIZE]{};av_strerror(openResult, errorText, sizeof(errorText));@@ -44,7 +52,10 @@ bool FFmpegDemuxer::open(const std::wstring& path)return false;}- if (avformat_find_stream_info(raw, nullptr) < 0) {+ interrupt_.arm();+ const int infoResult=avformat_find_stream_info(raw, nullptr);+ interrupt_.disarm();+ if (infoResult < 0) {log::error("media", "demuxer: avformat_find_stream_info failed");avformat_close_input(&raw);return false;@@ -98,6 +109,10 @@ int64_t FFmpegDemuxer::durationUs() constreturn context_->duration; // AV_TIME_BASE units == microseconds}+bool FFmpegDemuxer::seekable() const {+ return context_&&context_->pb&&(context_->pb->seekable&AVIO_SEEKABLE_NORMAL);+}+double FFmpegDemuxer::averageFps() const{if (context_ == nullptr) {@@ -199,7 +214,9 @@ bool FFmpegDemuxer::readVideoPacket(bool& endOfFile)// observable here (Playbook: every path frees exactly once - the// EOF/error paths below receive a blank packet either way).av_packet_unref(packet_);+ interrupt_.arm();const int result = av_read_frame(context_, packet_);+ interrupt_.disarm();if (result == AVERROR_EOF) {endOfFile = true;return false;@@ -235,7 +252,9 @@ bool FFmpegDemuxer::seekToUs(int64_t targetUs)}const int64_t target = av_rescale_q(targetUs, { 1, 1000000 },context_->streams[videoStreamIndex_]->time_base);+ interrupt_.arm();const int result = av_seek_frame(context_, videoStreamIndex_, target, AVSEEK_FLAG_BACKWARD);+ interrupt_.disarm();if (result < 0) {char errorText[AV_ERROR_MAX_STRING_SIZE]{};av_strerror(result, errorText, sizeof(errorText));diff --git a/src/sink/WasapiAudioSink.cpp b/src/sink/WasapiAudioSink.cppindex a4b4e159..ec5740b2 100644--- a/src/sink/WasapiAudioSink.cpp+++ b/src/sink/WasapiAudioSink.cpp@@ -1,6 +1,7 @@#include "veyra/sink/AudioGain.h"#include "veyra/sink/WasapiAudioSink.h"#include "veyra/engine/PlaybackRate.h"+#include "veyra/media/NetworkInput.h"#include <functiondiscoverykeys_devpkey.h>#include <propvarutil.h>#pragma comment(lib, "propsys.lib")@@ -32,17 +33,25 @@ AudioPipeline::~AudioPipeline()closeAll();}-bool AudioPipeline::open(const std::wstring& path)+bool AudioPipeline::open(const std::wstring& path,const std::atomic<bool>* cancelled){const int length=WideCharToMultiByte(CP_UTF8,0,path.data(),static_cast<int>(path.size()),nullptr,0,nullptr,nullptr);std::string narrow(length,'\0');WideCharToMultiByte(CP_UTF8,0,path.data(),static_cast<int>(path.size()),narrow.data(),length,nullptr,nullptr);fmt_=avformat_alloc_context();if(!fmt_)return false;- // Lets stopThread() abort a read that waits on slow storage.- fmt_->interrupt_callback={[](void* self)->int{return static_cast<AudioPipeline*>(self)->stopFlag_.load()?1:0;},this};- if (avformat_open_input(&fmt_, narrow.c_str(), nullptr, nullptr) != 0) return false;- if (avformat_find_stream_info(fmt_, nullptr) < 0) return false;+ inputInterrupt_.configure(media::networkMediaInput(path),cancelled,&stopFlag_);+ fmt_->interrupt_callback={media::InputInterrupt::callback,&inputInterrupt_};+ AVDictionary* options=nullptr;+ if(media::networkMediaInput(path))media::networkMediaOptions(&options);+ inputInterrupt_.arm();+ const int opened=avformat_open_input(&fmt_,narrow.c_str(),nullptr,&options);+ av_dict_free(&options);+ if(opened<0)return false;+ inputInterrupt_.arm();+ const int found=avformat_find_stream_info(fmt_,nullptr);+ inputInterrupt_.disarm();+ if(found<0)return false;tracks_.clear();for(unsigned i=0;i<fmt_->nb_streams;++i){const auto* stream=fmt_->streams[i];const auto* p=stream->codecpar;@@ -159,7 +168,9 @@ bool AudioPipeline::readPacket(AVPacket* packet)if(nextReadStall_!=std::chrono::steady_clock::time_point{})std::this_thread::sleep_for(std::chrono::duration<double,std::milli>(readStallMs_));nextReadStall_=std::chrono::steady_clock::now()+std::chrono::duration_cast<std::chrono::steady_clock::duration>(std::chrono::duration<double,std::milli>(readStallEveryMs_));}+ inputInterrupt_.arm();const int result=av_read_frame(fmt_,packet);+ inputInterrupt_.disarm();const double ms=std::chrono::duration<double,std::milli>(std::chrono::steady_clock::now()-begin).count();for(double seen=maxReadMs_.load();ms>seen&&!maxReadMs_.compare_exchange_weak(seen,ms);){}return result>=0;diff --git a/src/source/MediaFileSource.cpp b/src/source/MediaFileSource.cppindex 10f9e610..afeccba4 100644--- a/src/source/MediaFileSource.cpp+++ b/src/source/MediaFileSource.cpp@@ -64,9 +64,10 @@ bool MediaFileSource::fallbackToSoftware(std::string_view reason)const int64_t resumeUs = lastPtsUs_;veyra::log::warn("source-file", std::format("D3D12VA {} fallback to software reason={} path=redacted resumeUs={}", midStream ? "mid-stream" : "first-frame", reason, resumeUs));+ deinterlacer_.close();filterDraining_=false;decoder_.close();demuxer_.close();- if (!demuxer_.open(path_)) {+ if (!demuxer_.open(path_,cancelled_)) {veyra::log::error("source-file", "software fallback could not reopen demuxer");return false;}@@ -160,9 +161,11 @@ bool MediaFileSource::open(const SourceOpenDesc& desc){close();path_ = desc.path;+ cancelled_ = desc.cancelled;+ deinterlaceEnabled_=desc.deinterlace;filterDraining_=false;preferHardwareDecode_ = desc.preferHardwareDecode && desc.d3d12Device != nullptr && desc.d3d12Queue != nullptr;requireHardwareDecode_ = desc.requireHardwareDecode;- if (!demuxer_.open(desc.path)) {+ if (!demuxer_.open(desc.path,cancelled_)) {veyra::log::error("source-file", "demuxer open failed");return false;}@@ -293,9 +296,40 @@ SourceReadStatus MediaFileSource::read(pipeline::FramePacket& out, const AVFrameconst AVFrame* frame = nullptr;for (;;) {+ if(deinterlacer_.active()){+ const int result=deinterlacer_.receive(&frame);+ if(result>=0)break;+ if(result==AVERROR_EOF)return SourceReadStatus::Eos;+ if(result!=AVERROR(EAGAIN)||filterDraining_){errorMessage_=L"去隔行输出失败,请查看诊断";return SourceReadStatus::Error;}+ }frame = decoder_.receiveFrame();- if (frame != nullptr) { break; }+ if(frame){+ if(deinterlaceEnabled_&&((frame->flags&AV_FRAME_FLAG_INTERLACED)||deinterlacer_.active())){+ if(frame->width!=int(info_.width)||frame->height!=int(info_.height)||frame->decode_error_flags||(frame->flags&AV_FRAME_FLAG_CORRUPT)){+ errorMessage_=L"隔行视频画面损坏或尺寸改变,已停止处理";return SourceReadStatus::Error;+ }+ const auto* surface=decoder_.usingD3D11Frames()?&decoder_.hardwareSurface():nullptr;+ if(!deinterlacer_.active()){+ AVRational rate{demuxer_.nominalRateNum(),demuxer_.nominalRateDen()};+ if(demuxer_.averageFps()>0)rate=av_d2q(demuxer_.averageFps(),1000000);+ if(frame->duration>0)av_reduce(&rate.num,&rate.den,decoder_.frameTimeBaseDen(),frame->duration*decoder_.frameTimeBaseNum(),INT_MAX);+ if(!deinterlacer_.open(frame,surface,decoder_.frameTimeBaseNum(),decoder_.frameTimeBaseDen(),rate.num,rate.den)){+ errorMessage_=L"去隔行组件不可用或不支持当前格式;请关闭去隔行或改用软解";return SourceReadStatus::Error;+ }+ info_.deinterlaced=true;info_.deinterlacePath=deinterlacer_.path();+ info_.averageFps=av_q2d(rate)*2;info_.nominalRateNum=rate.num*2;info_.nominalRateDen=rate.den;+ }+ const int result=deinterlacer_.push(frame,surface);+ if(result<0){log::error("deinterlace",std::format("filter push failed code={}",result));errorMessage_=L"去隔行处理失败,请查看诊断";return SourceReadStatus::Error;}+ continue;+ }+ break;+ }if (decoder_.receiveStatus() == media::DecodeReceiveStatus::EndOfStream) {+ if(deinterlacer_.active()){+ if(deinterlacer_.push(nullptr)<0){errorMessage_=L"去隔行尾帧输出失败";return SourceReadStatus::Error;}+ filterDraining_=true;continue;+ }return SourceReadStatus::Eos;}if (decoder_.receiveStatus() == media::DecodeReceiveStatus::Error) {@@ -354,8 +388,8 @@ SourceReadStatus MediaFileSource::read(pipeline::FramePacket& out, const AVFrame++sequence_;out.sequence = sequence_;- const int tbNum = decoder_.frameTimeBaseNum();- const int tbDen = decoder_.frameTimeBaseDen();+ const int tbNum = deinterlacer_.active()?deinterlacer_.timeBaseNum():decoder_.frameTimeBaseNum();+ const int tbDen = deinterlacer_.active()?deinterlacer_.timeBaseDen():decoder_.frameTimeBaseDen();// Prefer the container PTS; fall back to FFmpeg's best-effort estimate and// finally the packet DTS. Raw elementary streams and some TS/AVI muxes// leave pts unset on individual frames, which used to stop playback@@ -449,7 +483,7 @@ SourceReadStatus MediaFileSource::read(pipeline::FramePacket& out, const AVFrame// Hardware surfaces that do not travel inside the AVFrame (D3D11VA) are// published per frame; every other path clears the field so the ingress// never sees a stale texture from an earlier frame.- if (decoder_.usingD3D11Frames()) {+ if (decoder_.usingD3D11Frames()&&frame->format==AV_PIX_FMT_D3D11) {const auto& view = decoder_.hardwareSurface();out.hardwareSurface.texture = view.texture;out.hardwareSurface.subresourceIndex = view.subresourceIndex;@@ -469,12 +503,14 @@ SourceReadStatus MediaFileSource::read(pipeline::FramePacket& out, const AVFramebool MediaFileSource::seek(const pipeline::Rational& targetSeconds){if (!info_.opened) { return false; }+ if(media::networkMediaInput(path_)&&!demuxer_.seekable())return false;if (targetSeconds.isUnknown() || targetSeconds.den == 0 || targetSeconds.isNegative()) {veyra::log::error("source-file", "seek target must be a known non-negative rational");return false;}const int64_t targetUs = rationalToUs(targetSeconds);if (!demuxer_.seekToUs(targetUs)) { return false; }+ deinterlacer_.close();filterDraining_=false;decoder_.flushBuffers();errorMessage_.clear();draining_ = false;@@ -490,12 +526,14 @@ bool MediaFileSource::seek(const pipeline::Rational& targetSeconds)void MediaFileSource::close() noexcept{errorMessage_.clear();+ deinterlacer_.close();filterDraining_=false;decoder_.close();demuxer_.close();info_ = SourceInfo{};path_.clear();preferHardwareDecode_ = false;requireHardwareDecode_ = false;+ cancelled_ = nullptr;}} // namespace veyra::sourcediff --git a/src/ui/QmlPlayerBridge.cpp b/src/ui/QmlPlayerBridge.cppindex e0ba3faf..05e9fbd6 100644--- a/src/ui/QmlPlayerBridge.cpp+++ b/src/ui/QmlPlayerBridge.cpp@@ -1,6 +1,7 @@#include "veyra/ui/QmlPlayerBridge.h"#include "veyra/gfx/PresentSink.h"#include "veyra/gfx/NvidiaVrr.h"+#include "veyra/media/NetworkInput.h"#include "veyra/ngx/DlssgLite.h"#include "veyra/RuntimePaths.h"#include "veyra/ui/GamePassthrough.h"@@ -4515,6 +4516,7 @@ QString QmlPlayerBridge::durationText() const { return mmss(impl_->snapshot.dura// --- source -----------------------------------------------------------------QString QmlPlayerBridge::sourceName() const {if (impl_->sourceLabel.empty()) return QString();+ if(impl_->liveKind==QLatin1String("url"))return tr("网络视频 · %1").arg(impl_->liveLabel);return QFileInfo(utf8Of(impl_->sourceLabel)).fileName();}QString QmlPlayerBridge::sourceSummary() const {@@ -5555,6 +5557,7 @@ void QmlPlayerBridge::openDroppedUrls(const QList<QUrl>& urls) {// append to the playlist; dropping inside PlaylistWindow always appends.if (urls.size() == 1) {const QUrl url = urls.front();+ if(!url.isLocalFile()){openUrl(url);return;}if (url.isLocalFile() && !QFileInfo(url.toLocalFile()).isDir()) { openUrl(url); return; }}impl_->playlist->addUrls(urls);@@ -5594,10 +5597,11 @@ void QmlPlayerBridge::tickPlaylist() {void QmlPlayerBridge::openPath(const QString& path) {if (path.isEmpty()) return;+ const bool network=media::networkMediaInput(wideOf(path));if (QFileInfo(path).isDir()) {impl_->playlist->addPaths({path}); emit playlistRequested(); return;}- if (PlaylistModel::supported(path) && !impl_->playlist->containsPath(path)) impl_->playlist->addPaths({path});+ if (!network&&PlaylistModel::supported(path) && !impl_->playlist->containsPath(path)) impl_->playlist->addPaths({path});impl_->playlistPath = path;impl_->playlist->setPlayback(path, QStringLiteral("opening"));rememberPosition(true);@@ -5612,10 +5616,11 @@ void QmlPlayerBridge::openPath(const QString& path) {impl_->sourceLabel = wide;impl_->liveKind.clear();impl_->liveLabel.clear();+ if(network){impl_->liveKind=QStringLiteral("url");impl_->liveLabel=QUrl(path).host();}++impl_->thumbnailGeneration;- emit thumbnailSourceChanged(path);+ emit thumbnailSourceChanged(network?QString():path);emit thumbnailGenerationChanged();- impl_->facade.noteRecentFile(wide);+ if(!network)impl_->facade.noteRecentFile(wide);emit recentFilesChanged();// Switch to a page with a video area, then settle the native window's// geometry, and only then open. The presenter samples the window's client@@ -5626,20 +5631,30 @@ void QmlPlayerBridge::openPath(const QString& path) {// design's source menu implies.if (impl_->currentPage.isEmpty() || impl_->currentPage == QLatin1String("home"))emit navigate(QStringLiteral("min"));- rememberSource(QStringLiteral("file"), path);+ if(!network)rememberSource(QStringLiteral("file"), path);if (impl_->preOpen) impl_->preOpen();auto options = impl_->options;options.softwareDecode = impl_->prefString("decode") == QLatin1String("software");options.hardwareDecodeOnly = impl_->prefString("decode") == QLatin1String("hardware");+ options.deinterlace=impl_->prefBool("deinterlace",true);impl_->engine.open(impl_->videoWindow, wide, options);impl_->openingSessionId = impl_->engine.snapshot().sessionId;- impl_->playlistSession = impl_->openingSessionId;+ impl_->playlistSession = network?0:impl_->openingSessionId;impl_->resumeSession = 0;if ((impl_->prefBool("rememberPosition", true)||impl_->prefBool("autoResume",false))) {const auto saved = impl_->prefs.value("positions").toMap().value(path).toMap();if (!saved.isEmpty()) { impl_->resumeSession = impl_->openingSessionId; impl_->resumeAt = saved.value("at").toDouble(); }}- refreshSubtitles(wide);+ refreshSubtitles(network?std::wstring():wide);+}++void QmlPlayerBridge::openNetworkDialog(){emit navigate(QStringLiteral("network"));}+bool QmlPlayerBridge::openNetworkAddress(const QString& address){+ const QUrl url(address.trimmed(),QUrl::StrictMode);+ if(!url.isValid()||url.host().isEmpty()||!media::networkMediaInput(wideOf(url.scheme()+QStringLiteral(":")))){+ emit notice(tr("请输入有效的 HTTP、HTTPS 或 RTSP 视频地址"),true);return false;+ }+ openPath(url.adjusted(QUrl::RemoveFragment).toString(QUrl::FullyEncoded));return true;}void QmlPlayerBridge::togglePlayPause() {@@ -5648,6 +5663,9 @@ void QmlPlayerBridge::togglePlayPause() {const auto& s = impl_->snapshot;using T = engine::TransportState;if (s.image || s.transport == T::Opening || s.transport == T::Stopping) return;+ if(impl_->liveKind==QLatin1String("url")&&(s.transport==T::Ended||(s.transport==T::Paused&&s.duration<=0))){+ openNetworkAddress(QString::fromStdWString(impl_->sourceLabel));return;+ }// Capture cards and streams pause too (field request 2026-10-02): the engine stops// reading and enhancing, keeps the last picture and resets the source's queue, so// play resumes with the newest frame rather than a backlog. The connection stays up.@@ -5683,6 +5701,7 @@ void QmlPlayerBridge::seekBy(double seconds) {impl_->engine.seek(std::max(0.0, impl_->snapshot.position + seconds));}void QmlPlayerBridge::openUrl(const QUrl& url) {+ if(!url.isLocalFile()){openNetworkAddress(url.toString(QUrl::FullyEncoded));return;}if (!url.isLocalFile()) {emit notice(tr("只能打开本地文件"), true);return;@@ -7066,7 +7085,7 @@ void QmlPlayerBridge::updateRunStatus() {}if(i.presentation.variableRefresh){if(vrrLevel>=4)options<<tr("可变刷新 · 生效中");- else if(vrrLevel==3)options<<tr("可变刷新 · 未生效");+ else if(vrrLevel==3)options<<tr("可变刷新 · 等待驱动确认");else options<<tr("可变刷新 · 当前屏幕不可用");}else if(s.running&&vrrLevel>=4)options<<tr("屏幕可变刷新生效中");if(i.presentation.outputRate!=engine::OutputRateMode::Off){@@ -7412,11 +7431,11 @@ QString QmlPlayerBridge::vrrHint() const {switch (impl_->vrrState) {case 0: return tr("无法检测屏幕是否支持(目前只支持 NVIDIA 显卡)");case 1: return tr("当前屏幕不支持可变刷新");- case 2: return tr("屏幕支持,但驱动未开启:NVIDIA 控制面板 → 设置 G-SYNC");+ case 2: return tr("屏幕支持可变刷新,但当前显示模式不可用;请检查连接、刷新率及驱动设置");case 3:if (!on) return tr("屏幕跟着画面刷新:不撕裂,也几乎不用等刷新");- return running ? tr("已开启,屏幕还没进入可变刷新:全屏并隐藏控制栏,或在 NVIDIA 控制面板为窗口模式开启 G-SYNC")- : tr("已开启,播放时生效");+ return running ? tr("已请求可变刷新,驱动尚未确认生效;可检查窗口/全屏 G-SYNC 设置,当前状态不代表驱动已关闭")+ : tr("已开启,将在播放时请求可变刷新;是否生效以驱动报告为准");default: return on ? tr("生效中:屏幕跟着画面刷新") : tr("屏幕正处于可变刷新(驱动已开启)");}}@@ -7683,6 +7702,7 @@ QString QmlPlayerBridge::sourceKind() const {QString QmlPlayerBridge::sourceTitle() const {const QString kind = sourceKind();if (kind.isEmpty()) return {};+ if(kind==QLatin1String("url"))return tr("网络视频 · %1").arg(impl_->liveLabel);if (kind == QLatin1String("file") || kind == QLatin1String("image")) return sourceName();if (kind == QLatin1String("capture")) {const QString name = impl_->prefString("captureDeviceName");diff --git a/tests/integration/NetworkInterlaceTests.cpp b/tests/integration/NetworkInterlaceTests.cppnew file mode 100644index 00000000..02eb9c7e--- /dev/null+++ b/tests/integration/NetworkInterlaceTests.cpp@@ -0,0 +1,91 @@+#include "veyra/source/MediaFileSource.h"+#include "veyra/gfx/D3D12DeviceContext.h"+#include "veyra/Log.h"+#include <chrono>+#include <thread>+#include <filesystem>+#include <fstream>+#include <iostream>+#include <cmath>+extern "C" {+#include <libavutil/hwcontext.h>+}+using namespace veyra;+int wmain(int argc,wchar_t** argv){+ if(argc<3)return 2;+ std::atomic<bool> cancel=false;+ source::SourceOpenDesc desc;desc.path=argv[1];desc.cancelled=&cancel;+ if(std::wstring_view(argv[2])==L"cancel"){+ desc.preferHardwareDecode=false;+ std::jthread stop([&]{std::this_thread::sleep_for(std::chrono::milliseconds(200));cancel=true;});+ source::MediaFileSource input;const auto start=std::chrono::steady_clock::now();const bool opened=input.open(desc);+ const auto ms=std::chrono::duration<double,std::milli>(std::chrono::steady_clock::now()-start).count();+ std::cout<<"CANCEL opened="<<opened<<" milliseconds="<<ms<<std::endl;return !opened&&ms<2500?0:1;+ }+ if(argc<7)return 2;+ desc.preferHardwareDecode=std::wstring_view(argv[2])==L"hardware";+ desc.requireHardwareDecode=desc.preferHardwareDecode;+ desc.deinterlace=std::wstring_view(argv[3])==L"on";+ const int expected=_wtoi(argv[4]);const double fps=_wtof(argv[5]);+ const std::filesystem::path out=argv[6];std::filesystem::create_directories(out);+ Logger::instance().openFile((out/L"source.log").wstring());Logger::instance().setConsoleEnabled(false);+ gfx::D3D12DeviceContext device;Status status=Status::Ok;+ if(desc.preferHardwareDecode){+ gfx::DeviceContextDesc options;options.enableDebugLayer=true;+ if(!device.initialize(options,status))return 3;+ desc.d3d12Device=device.device();desc.d3d12Queue=device.directQueue();desc.d3d12AdapterLuid=device.adapter().luid;+ }+ source::MediaFileSource input;+ if(!input.open(desc)){std::wcerr<<L"OPEN FAILED "<<input.errorMessage()<<std::endl;return 1;}+ int failures=0;auto check=[&](bool ok,const char* name){failures+=!ok;std::cout<<(ok?"PASS ":"FAIL ")<<name<<std::endl;};+ for(int pass=0;pass<2;++pass){+ if(pass){+ if(media::networkMediaInput(desc.path))break;+ check(input.seek({0,1}),"seek after EOF resets decoder and filter");+ }+ unsigned count=0;double last=-1e30,first=-1,comb=0;bool chronological=true,progressive=true;+ const AVFrame* decoded=nullptr;pipeline::FramePacket packet;source::SourceReadStatus result;+ while((result=input.read(packet,&decoded))==source::SourceReadStatus::Frame){+ check(decoded!=nullptr,"decoded field exists");if(!decoded)break;+ const double seconds=packet.pts.toDouble();+ if(count==0)first=seconds;+ chronological=chronological&&!packet.pts.isUnknown()&&seconds>last;+ if(count&&fps>0)check(std::abs((seconds-last)-1/fps)<0.0001,"field PTS has requested real cadence");+ if(pass&&count==0)check(packet.flags&uint32_t(pipeline::FrameFlagBits::Seek),"first post-seek field carries seek reset");+ last=seconds;progressive=progressive&&!(decoded->flags&AV_FRAME_FLAG_INTERLACED);+ AVFrame* downloaded=nullptr;const AVFrame* pixels=decoded;+ if(decoded->format==AV_PIX_FMT_D3D12||decoded->format==AV_PIX_FMT_D3D11){+ // Explicit diagnostic readback only. Production source/filter+ // never transfers a GPU frame to CPU memory.+ downloaded=av_frame_alloc();+ check(downloaded&&av_hwframe_transfer_data(downloaded,decoded,0)>=0,"diagnostic GPU readback succeeds");+ pixels=downloaded;+ }+ if(pixels&&pixels->data[0]){+ double energy=0;+ for(int y=1;y<decoded->height-1;++y)for(int x=0;x<decoded->width;++x){+ const int a=pixels->data[0][ptrdiff_t(y-1)*pixels->linesize[0]+x];+ const int b=pixels->data[0][ptrdiff_t(y)*pixels->linesize[0]+x];+ const int c=pixels->data[0][ptrdiff_t(y+1)*pixels->linesize[0]+x];+ energy+=std::abs(a-2*b+c);+ }+ comb+=energy/double(decoded->width*(decoded->height-2));+ if(pass==0&&count<4){+ std::ofstream image(out/(L"field-"+std::to_wstring(count)+L".pgm"),std::ios::binary);+ image<<"P5\n"<<decoded->width<<" "<<decoded->height<<"\n255\n";+ for(int y=0;y<decoded->height;++y)image.write(reinterpret_cast<const char*>(pixels->data[0]+ptrdiff_t(y)*pixels->linesize[0]),decoded->width);+ }+ }+ av_frame_free(&downloaded);++count;+ if(expected<0&&count>=120)break;+ if(count>1000){check(false,"output remains bounded");break;}+ }+ if(expected>=0){check(result==source::SourceReadStatus::Eos,"all tail fields drain to EOF");check(int(count)==expected,"exact field/frame count including EOF");}+ check(chronological,"PTS strictly increases across every field");+ if(desc.deinterlace)check(progressive,"interlaced fields are delivered as progressive frames");+ if(fps>0)check(std::abs(input.info().averageFps-fps)<0.01,"source metadata reports actual progressive rate");+ std::cout<<"RESULT pass="<<pass<<" count="<<count<<" first="<<first<<" last="<<last<<" comb="<<(count?comb/count:0)<<" deinterlace="<<input.info().deinterlacePath<<" hardware="<<input.info().hardwareDecodeActive<<" failures="<<failures<<std::endl;+ if(result==source::SourceReadStatus::Error)std::wcerr<<input.errorMessage()<<std::endl;+ }+ input.close();return failures?1:0;+}diff --git a/tests/unit/RepairContractTests.cpp b/tests/unit/RepairContractTests.cppindex cd01981c..7362fdbd 100644--- a/tests/unit/RepairContractTests.cpp+++ b/tests/unit/RepairContractTests.cpp@@ -37,9 +37,29 @@ int thunkReplacementFunction(int value) { ++thunkHookCalls; return thunkOriginal#include "veyra/engine/Subtitles.h"#include "veyra/engine/PresentationSettings.h"#include "veyra/engine/PresentationGeometry.h"+#include "veyra/gfx/NvidiaVrr.h"int main(){using namespace veyra;int failures=0,checks=0;auto check=[&](bool ok,const char* name){++checks;if(!ok)++failures;std::cout<<(ok?"PASS ":"FAIL ")<<name<<'\n';};+ {+ gfx::VrrState state;state.known=state.capsKnown=true;+ state.supportsVrr=state.currentlyCapable=true;+ check(!state.trueGsync&&!state.possible&&!state.requested&&gfx::vrrLevel(state)==3,+ "issue45 adaptive-sync applied mode can request VRR before driver activity flags appear");+ check(!state.enabled&&!state.inVrrMode,+ "VRR presentation eligibility does not fabricate active driver flags");+ state.currentlyCapable=false;+ check(gfx::vrrLevel(state)==2&&!gfx::vrrPresentationAvailable(state),+ "VRR panel in incompatible display mode does not opt into VRR presentation");+ state.supportsVrr=false;+ check(gfx::vrrLevel(state)==1,"non-VRR display remains unsupported");+ state.possible=true;+ check(gfx::vrrLevel(state)==3,"driver VRR possibility remains sufficient without generic caps");+ state.enabled=true;+ check(gfx::vrrLevel(state)==4,"only real activity flags report VRR active");+ state={};+ check(gfx::vrrLevel(state)==0,"unanswered VRR query remains unknown");+ }{engine::PreviewView v;v.displayAspect=16.0/9;auto [w,h]=v.renderedSize(1000,1000,1440,1080);