Skip to content

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(capture): 60->30 keeps the first copy of each 30 fps picture

Veyra Goal Agent54c942e1254b
diff --git a/docs/CAPTURE_FPS_AUDIO_REPORT_2026-10-27.md b/docs/CAPTURE_FPS_AUDIO_REPORT_2026-10-27.md
index df8858cb..bbb08e03 100644
--- a/docs/CAPTURE_FPS_AUDIO_REPORT_2026-10-27.md
+++ b/docs/CAPTURE_FPS_AUDIO_REPORT_2026-10-27.md
@@ -141,3 +141,31 @@ PS5 设为“位流(杜比/DTS)”时,会把含中置的 5.1 以 IEC 61937
- 界面合同、翻译、QtQuick(117 通过、1 跳过)通过。
- `scripts/acceptance/shortcut-defaults.py`:私有配置下全新默认为 F7/F8;全屏已占 F8 时,全屏保留 F8、录制为空;设置页两行都在,没有 QML 错误。
- 没有往真实程序里注入按键做端到端截图/录制。
+
+## 5. 60→30 取第一份;采集驱动缓冲(2026-10-28)
+
+### 60→30 取每个画面的第一份
+
+- **问题**:30 帧游戏在 60 Hz 采集里每个画面出现两次。原来的 60→30 只按时间每隔一个样本取一个;如果相位落在第二份上,每个画面都会晚 16.7 ms 才进入 GPU。
+- **改法**:60→30 模式下也打开采集回调里已有的整帧比对(`PictureCompare.h`)。引擎只读取回调算好的画面编号,引擎线程不额外做整帧比较。`CaptureHalfRate` 连续 3 次取到“与前一个样本相同的画面”时,接着取下一个样本(新画面的第一份),之后的网格从这里继续。60 帧游戏不会重复,不规则帧率的游戏也不会连续 3 次取到第二份,所以这两种情况的取帧结果与原来逐帧一致。没有画面编号时(MJPG 等 CPU 解码帧、硬件帧),行为不变。
+- **单元测试**:
+ - 30 帧内容落在第二份上时只挪动一次,不丢画面,仍为每秒 30 帧。
+ - 已在第一份上时不挪动。
+ - 60 帧内容和 45 帧内容的取帧与原来逐帧相同。
+- **实卡(MCS 4K-T911,1440p60 P010,PS5 运行中的 30 帧游戏,用户配置的只读副本)**:开头 4 帧都取到第二份后挪动;之后约 23 秒 702 个保留帧里只有 19 帧是第二份(2.7%)。游戏偶尔掉节奏使相位翻转,3 帧内会挪回来,全程共挪动 5 次。上一轮 PS5 停在静止画面时,每个样本都与前一个相同,没有可挪到的新画面,所以不挪动,这是正确的行为。
+
+### 采集驱动缓冲
+
+- **建议缓冲数被无视**:`IAMBufferNegotiation` 建议 1/3 个,驱动实际都是 10 个。T911 用探针和 Veyra 都测过,G50 看的是现场日志。
+- **缓冲数不是延迟来源**:探针(`scripts/acceptance/dshow-latency-probe.cpp`,结果见 `reports/.../dshow-latency-probe.txt`)显示送达间隔稳定(P50 16.67–16.79 ms,P95 ≤16.86 ms,没有一次 4 ms 内连到两帧)。驱动是完成一帧交一帧,帧没有在这 10 个缓冲里排队,所以即使驱动接受少缓冲,延迟也不会降。
+- **T911 各格式的时间戳语义不同**:
+ - NV12、MJPG 在送达时才打时间戳,“驱动延迟”约为 0,看不出卡内延迟。
+ - P010 1440p60 的时间戳打得早,Veyra 实测从打时间戳到回调稳定约 77 ms。有一轮(PS5 静止画面)P010 只送了 59.54 帧,而时间戳是 59.99 帧,延迟一路累积到 250 ms 以上。
+ - P010 1440p60 每秒要传 663 MB,NV12 是 332 MB。
+- **结论**:软件这一端没有能降低驱动延迟的开关。SDR 信号改用 NV12 更稳妥,但它是否真的比 P010 快,需要用手机 240 帧慢动作同时拍电视和采集画面来比对,软件里测不出来。
+
+### 未验证
+
+- 采集卡端到端(玻璃到玻璃)延迟。
+- NV12 与 P010 的真实延迟差。
+- 60→30 挪动后的画面实际早到多少(理论上每个画面早 16.7 ms,没有用光学方法测)。
diff --git a/docs/WORKLOG.md b/docs/WORKLOG.md
index 58662f9f..978f83b0 100644
--- a/docs/WORKLOG.md
+++ b/docs/WORKLOG.md
@@ -12,6 +12,8 @@
- 快捷键:截图默认Ctrl+S→F7,新增录制F8,可在设置改;游戏模式钩子扩为面板/退出/截图/录制四槽,仅在游戏或Veyra在前台时接管。老配置已占F7/F8时保留原功能、新项未设置。game_passthrough/UI合同/翻译/QtQuick及私有配置启动检查通过。
+- 60→30:采集回调画面编号用于相位,连续3次第二份即挪到第一份;60帧/不规则内容取帧不变。实卡T911+PS5 30帧游戏:702保留帧中第二份19(2.7%),挪动5次。驱动缓冲:建议1/3均被无视(实际10),送达均匀无排队,缓冲不是延迟来源;T911 P010 1440p60时间戳到回调约77ms且曾跌到59.54帧累积,SDR建议NV12(需慢动作实拍确认)。
+
构建build-recording-handoff --task claude-capture-fps-audio-20261027(首轮--reconfigure 79.4秒,其后增量)。未验证:用户165Hz实机与游戏模式、G50位流透传、无该属性的旧Windows。
## 2026-10-27 项目整理1–4
diff --git a/include/veyra/engine/CaptureHalfRate.h b/include/veyra/engine/CaptureHalfRate.h
index c934e809..225ad5db 100644
--- a/include/veyra/engine/CaptureHalfRate.h
+++ b/include/veyra/engine/CaptureHalfRate.h
@@ -5,21 +5,46 @@ namespace veyra::engine {
// Explicit 60/59.94 transport -> 30/29.97 sampling before any GPU work.
// Keeps original PTS. It does not claim to detect unique pictures or repair
// irregular game cadence. Quarter-slot tolerance absorbs timestamp jitter.
+//
+// Phase (2026-10-27): a 30 fps game in 60 Hz shows every picture twice, and
+// every second sample may sit on the second copies, so each picture reaches the
+// GPU 16.7 ms after it arrived. With picture numbers (PictureCompare.h) a kept
+// sample that shows the picture of the sample just before it is such a second
+// copy; after kSecondCopies in a row the next sample, a first copy, is taken as
+// well and the grid continues from it. 60 fps content never repeats and
+// irregular content does not repeat on every kept sample, so both keep the
+// plain grid; without picture numbers nothing changes.
class CaptureHalfRate {
public:
- void reset(){anchored_=false;}
+ static constexpr unsigned kSecondCopies=3;
+ void reset(){anchored_=false;havePicture_=false;shift_=false;secondCopies_=0;}
static bool supported(double fps){return std::isfinite(fps)&&fps>=59&&fps<=61;}
- bool accept(int64_t pts,int64_t transportInterval,bool boundary){
+ // picture: the sample's picture number, nullptr when unknown.
+ bool accept(int64_t pts,int64_t transportInterval,bool boundary,const uint64_t* picture=nullptr){
+ const bool repeat=picture&&havePicture_&&*picture==lastPicture_;
+ havePicture_=picture!=nullptr;if(picture)lastPicture_=*picture;
if(boundary||!anchored_||pts<last_||pts-last_>transportInterval*6){
- anchored_=true;next_=pts+transportInterval*2;last_=pts;return true;
+ anchored_=true;next_=pts+transportInterval*2;last_=pts;shift_=false;secondCopies_=repeat?1:0;return true;
}
last_=pts;
- if(pts+transportInterval/4<next_)return false;
+ if(pts+transportInterval/4<next_){
+ if(!shift_||!picture||repeat)return false;
+ // The first copy of the next picture: move the grid onto it.
+ shift_=false;secondCopies_=0;next_=pts+transportInterval*2;++shifts_;return true;
+ }
const auto period=transportInterval*2;
next_+=((pts+transportInterval/4-next_)/period+1)*period;
+ secondCopies_=repeat?secondCopies_+1:0;
+ shift_=secondCopies_>=kSecondCopies;
+ ++grid_;secondKept_+=repeat;
return true;
}
+ uint64_t shifts()const{return shifts_;}
+ // Samples the grid kept, and how many of them were second copies (diagnostics).
+ uint64_t gridKept()const{return grid_;}
+ uint64_t secondCopiesKept()const{return secondKept_;}
private:
- bool anchored_=false;int64_t next_=0,last_=0;
+ bool anchored_=false,havePicture_=false,shift_=false;int64_t next_=0,last_=0;
+ uint64_t lastPicture_=0,shifts_=0,grid_=0,secondKept_=0;unsigned secondCopies_=0;
};
}
diff --git a/scripts/acceptance/capture-latency-round.py b/scripts/acceptance/capture-latency-round.py
new file mode 100644
index 00000000..35f9d54b
--- /dev/null
+++ b/scripts/acceptance/capture-latency-round.py
@@ -0,0 +1,75 @@
+"""One capture-card round for 60->30 phase and driver buffering (claude-capture-fps-audio-20261027).
+
+1. dshow_latency_probe (tmp/<task>/bench) measures the driver's frame age for the user's
+ current format with no / 1 / 3 suggested buffers and for a few other formats.
+2. This tree's build captures for 30 s on a private profile seeded read-only from the
+ user's user-data (device, format, 60->30, effect chain); the log shows the picture
+ compare, the 60->30 phase and the driver age.
+The user's own player must be closed first (the capture card is exclusive).
+usage: py -3.11 -X utf8 -B -I scripts/acceptance/capture-latency-round.py [--app-only]
+"""
+from pathlib import Path
+import hashlib, json, os, re, shutil, subprocess, time
+
+B = Path('E:/项目/Veyra'); T = 'claude-capture-fps-audio-20261027'; R = Path(__file__).resolve().parents[2]
+D = B/'build/claude-screen-recording-20261022'; A = B/'tests'/T/'app'; P = B/'tests'/T/'profile-capture'
+L = B/'logs'/T/'capture-round'; TMP = B/'tmp'/T/'capture-round'; OUT = B/'reports'/T
+PROBE = B/'tmp'/T/'bench/dshow_latency_probe.exe'
+USER_DATA = Path('E:/App/Veyra-2.1.0-test-NVIDIA-win64-portable/runtime_local/user-data-2.0.0')
+for p in [L, TMP, OUT]: p.mkdir(parents=True, exist_ok=True)
+running = subprocess.check_output(['tasklist', '/fo', 'csv', '/nh'], text=True, errors='replace')
+assert not any(l.lower().startswith(('"veyra', '"obs64', '"obs32')) for l in running.splitlines()), 'another program may hold the capture card'
+assert (A/'veyra_qml_ui.exe').exists(), 'run screen-capture-rate.py --exe build first (it stages the app)'
+
+
+def sha(p):
+ with p.open('rb') as f: return hashlib.file_digest(f, 'sha256').hexdigest()
+
+
+def replace(p, data):
+ p.parent.mkdir(parents=True, exist_ok=True)
+ if p.exists(): p.unlink()
+ p.write_bytes(data)
+
+
+# 1. Driver buffering probe (--app-only skips it).
+import sys
+probe = []
+for args in [] if '--app-only' in sys.argv else [('2560', '1440', '60', 'P010', '0'), ('2560', '1440', '60', 'P010', '1'), ('2560', '1440', '60', 'P010', '3'),
+ ('2560', '1440', '60', 'NV12', '0'), ('1920', '1080', '60', 'NV12', '0'), ('2560', '1440', '120', 'NV12', '0'),
+ ('2560', '1440', '60', 'MJPG', '0')]:
+ out = subprocess.run([str(PROBE), 'run', 'T911', *args, '6'], capture_output=True, text=True, timeout=60)
+ line = next((l for l in out.stdout.splitlines() if l.startswith(('RUN', 'FORMAT', 'CONNECT', 'DEVICE', 'PIN'))), out.stdout.strip()[-200:])
+ probe.append(dict(args=args, exit=out.returncode, line=line)); print(line, flush=True)
+ time.sleep(1)
+
+# 2. The build on the user's capture setup (copied, never modified at the source).
+replace(A/'veyra_qml_ui.exe', (D/'veyra_qml_ui.exe').read_bytes())
+for folder in ['qml', 'i18n']:
+ for p in (R/folder).rglob('*'):
+ if p.is_file(): replace(A/folder/p.relative_to(R/folder), p.read_bytes())
+if P.exists(): shutil.rmtree(P)
+P.mkdir(parents=True)
+seeded = {}
+for f in USER_DATA.iterdir():
+ if f.is_file(): shutil.copyfile(f, P/f.name); seeded[f.name] = sha(f)
+prefs = json.loads((P/'qml-preferences.v1.json').read_text('utf8'))
+prefs.update(autoResume=True, prewarmEnhancement=False, screenshotDir=str(TMP))
+(P/'qml-preferences.v1.json').write_text(json.dumps(prefs, ensure_ascii=False), 'utf8')
+env = {k: v for k, v in os.environ.items() if not k.upper().startswith(('VEYRA_', 'QT_', 'QSG_', 'QML_'))}
+log_file = L/'engine.log'; console = L/'console.log'
+for f in (log_file, console):
+ if f.exists(): f.unlink()
+env.update(TEMP=str(TMP), TMP=str(TMP), APPDATA=str(P/'AppData'), LOCALAPPDATA=str(P/'LocalAppData'), CUDA_CACHE_PATH=str(TMP/'cuda'),
+ QML_DISABLE_DISK_CACHE='1', QT_FORCE_STDERR_LOGGING='1', VEYRA_LOG_FILE=str(log_file))
+with console.open('wb') as f:
+ run = subprocess.run([str(A/'veyra_qml_ui.exe'), '--page', 'pro', '--size', '1600x900', '--data-dir', str(P), '--exit-after', '40000'],
+ cwd=A, env=env, stdout=f, stderr=subprocess.STDOUT, timeout=90)
+lines = log_file.read_text('utf8', errors='replace').splitlines()
+grab = lambda tag: [l.split('] ', 2)[-1] for l in lines if tag in l]
+result = dict(probe=probe, app=dict(exit=run.returncode, userDataUntouched=all(sha(USER_DATA/n) == d for n, d in seeded.items()),
+ pictureCompare=grab('[capture-dedup] picture compare'), phase=grab('60->30 phase'), captureRate=grab('[capture-rate] revision')[:4],
+ driverAge=grab('[capture-driver-age]'), buffer=grab('[capture-buffer]'), format=grab('[capture] selected')[:2] or grab('native ConnectDirect')[:2],
+ frameRate=grab('[frame-rate]')[-3:], timing=[l[:400] for l in grab('[capture-timing]')[-2:]], log=str(log_file)))
+(OUT/'capture-latency-round.json').write_text(json.dumps(result, ensure_ascii=False, indent=1), 'utf8')
+print(json.dumps(result['app'], ensure_ascii=False, indent=1))
diff --git a/scripts/acceptance/dshow-latency-probe.cpp b/scripts/acceptance/dshow-latency-probe.cpp
new file mode 100644
index 00000000..eecb946a
--- /dev/null
+++ b/scripts/acceptance/dshow-latency-probe.cpp
@@ -0,0 +1,177 @@
+// claude-capture-fps-audio-20261027: what a DirectShow capture card's driver does with a
+// smaller buffer request, and how old its frames are when they reach user mode.
+// dshow_latency_probe list <device-substring>
+// dshow_latency_probe run <device-substring> <width> <height> <fps> <NV12|YUY2|MJPG|any> <buffers 0=none> <seconds>
+// Age = graph clock at the callback - (explicit run start + sample start time): what the
+// driver stamped the frame with versus when it arrives (same measure as Veyra's
+// [capture-driver-age], but with an exact run start). Interval stats show queueing:
+// a queue delivers in bursts or with ages that step by whole frames.
+#include <windows.h>
+#include <dshow.h>
+#include <dvdmedia.h>
+#include <wrl/client.h>
+#include <algorithm>
+#include <atomic>
+#include <cstdio>
+#include <mutex>
+#include <string>
+#include <vector>
+#pragma comment(lib, "strmiids.lib")
+#pragma comment(lib, "ole32.lib")
+#pragma comment(lib, "oleaut32.lib")
+using Microsoft::WRL::ComPtr;
+
+MIDL_INTERFACE("0579154A-2B53-4994-B0D0-E773148EFF85")
+ISampleGrabberCB : public IUnknown {
+public:
+ virtual HRESULT STDMETHODCALLTYPE SampleCB(double, IMediaSample*) = 0;
+ virtual HRESULT STDMETHODCALLTYPE BufferCB(double, BYTE*, long) = 0;
+};
+MIDL_INTERFACE("6B652FFF-11FE-4fce-92AD-0266B5D7C78F")
+ISampleGrabber : public IUnknown {
+public:
+ virtual HRESULT STDMETHODCALLTYPE SetOneShot(BOOL) = 0;
+ virtual HRESULT STDMETHODCALLTYPE SetMediaType(const AM_MEDIA_TYPE*) = 0;
+ virtual HRESULT STDMETHODCALLTYPE GetConnectedMediaType(AM_MEDIA_TYPE*) = 0;
+ virtual HRESULT STDMETHODCALLTYPE SetBufferSamples(BOOL) = 0;
+ virtual HRESULT STDMETHODCALLTYPE GetCurrentBuffer(long*, long*) = 0;
+ virtual HRESULT STDMETHODCALLTYPE GetCurrentSample(IMediaSample**) = 0;
+ virtual HRESULT STDMETHODCALLTYPE SetCallback(ISampleGrabberCB*, long) = 0;
+};
+static const CLSID kSampleGrabber = {0xC1F400A0, 0x3F08, 0x11d3, {0x9F, 0x0B, 0x00, 0x60, 0x08, 0x03, 0x9E, 0x37}};
+static const CLSID kNullRenderer = {0xC1F400A4, 0x3F08, 0x11d3, {0x9F, 0x0B, 0x00, 0x60, 0x08, 0x03, 0x9E, 0x37}};
+
+GUID fourccGuid(const char* f) { GUID g = MEDIASUBTYPE_YUY2; g.Data1 = DWORD(f[0]) | DWORD(f[1]) << 8 | DWORD(f[2]) << 16 | DWORD(f[3]) << 24; return g; }
+std::string fourccName(const GUID& g) {
+ if (g == MEDIASUBTYPE_RGB24) return "RGB24"; if (g == MEDIASUBTYPE_RGB32) return "RGB32";
+ char s[5] = {char(g.Data1 & 255), char((g.Data1 >> 8) & 255), char((g.Data1 >> 16) & 255), char((g.Data1 >> 24) & 255), 0};
+ for (char& c : s) if (c && (c < 32 || c > 126)) c = '?';
+ return s;
+}
+void freeType(AM_MEDIA_TYPE* t) { if (!t) return; if (t->cbFormat) CoTaskMemFree(t->pbFormat); if (t->pUnk) t->pUnk->Release(); CoTaskMemFree(t); }
+bool dims(const AM_MEDIA_TYPE* t, LONG& w, LONG& h, REFERENCE_TIME*& interval) {
+ if (t->formattype == FORMAT_VideoInfo && t->cbFormat >= sizeof(VIDEOINFOHEADER)) {
+ auto* v = reinterpret_cast<VIDEOINFOHEADER*>(t->pbFormat); w = v->bmiHeader.biWidth; h = std::abs(v->bmiHeader.biHeight); interval = &v->AvgTimePerFrame; return true;
+ }
+ if (t->formattype == FORMAT_VideoInfo2 && t->cbFormat >= sizeof(VIDEOINFOHEADER2)) {
+ auto* v = reinterpret_cast<VIDEOINFOHEADER2*>(t->pbFormat); w = v->bmiHeader.biWidth; h = std::abs(v->bmiHeader.biHeight); interval = &v->AvgTimePerFrame; return true;
+ }
+ return false;
+}
+double nowMs() { static LARGE_INTEGER f{}; if (!f.QuadPart) QueryPerformanceFrequency(&f); LARGE_INTEGER c; QueryPerformanceCounter(&c); return double(c.QuadPart) * 1000.0 / double(f.QuadPart); }
+
+ComPtr<IBaseFilter> findDevice(const std::wstring& part, std::wstring& name) {
+ ComPtr<ICreateDevEnum> devEnum; ComPtr<IEnumMoniker> e;
+ if (FAILED(CoCreateInstance(CLSID_SystemDeviceEnum, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&devEnum))) ||
+ devEnum->CreateClassEnumerator(CLSID_VideoInputDeviceCategory, &e, 0) != S_OK) return nullptr;
+ for (ComPtr<IMoniker> m; e->Next(1, &m, nullptr) == S_OK; m.Reset()) {
+ ComPtr<IPropertyBag> bag; VARIANT v; VariantInit(&v);
+ if (FAILED(m->BindToStorage(nullptr, nullptr, IID_PPV_ARGS(&bag))) || FAILED(bag->Read(L"FriendlyName", &v, nullptr))) continue;
+ std::wstring n = v.bstrVal; VariantClear(&v);
+ if (n.find(part) == std::wstring::npos) continue;
+ ComPtr<IBaseFilter> f; if (SUCCEEDED(m->BindToObject(nullptr, nullptr, IID_PPV_ARGS(&f)))) { name = n; return f; }
+ }
+ return nullptr;
+}
+
+struct Grab : ISampleGrabberCB {
+ std::mutex mutex; std::vector<double> ages, arrivals, streamMs; ComPtr<IReferenceClock> clock; REFERENCE_TIME start = 0;
+ ULONG STDMETHODCALLTYPE AddRef() override { return 2; } ULONG STDMETHODCALLTYPE Release() override { return 1; }
+ HRESULT STDMETHODCALLTYPE QueryInterface(REFIID id, void** p) override {
+ if (id == IID_IUnknown || id == __uuidof(ISampleGrabberCB)) { *p = this; return S_OK; } *p = nullptr; return E_NOINTERFACE;
+ }
+ HRESULT STDMETHODCALLTYPE SampleCB(double, IMediaSample* s) override {
+ const double arrival = nowMs(); REFERENCE_TIME now = 0, b = 0, e = 0;
+ if (clock && SUCCEEDED(clock->GetTime(&now)) && SUCCEEDED(s->GetTime(&b, &e))) {
+ std::lock_guard lock(mutex); ages.push_back(double(now - start - b) / 1e4); arrivals.push_back(arrival); streamMs.push_back(double(b) / 1e4);
+ }
+ return S_OK;
+ }
+ HRESULT STDMETHODCALLTYPE BufferCB(double, BYTE*, long) override { return S_OK; }
+};
+
+double pct(std::vector<double> v, double q) { if (v.empty()) return -1; std::sort(v.begin(), v.end()); return v[std::min(v.size() - 1, size_t(q * (v.size() - 1) + .5))]; }
+
+int main(int argc, char** argv) {
+ CoInitializeEx(nullptr, COINIT_MULTITHREADED);
+ if (argc < 3) { std::printf("usage: list <device> | run <device> <w> <h> <fps> <fourcc|any> <buffers> <seconds>\n"); return 1; }
+ const std::string mode = argv[1]; std::wstring part(argv[2], argv[2] + strlen(argv[2])), name;
+ auto device = findDevice(part, name);
+ if (!device) { std::printf("DEVICE not found\n"); return 2; }
+ ComPtr<IGraphBuilder> graph; ComPtr<ICaptureGraphBuilder2> builder;
+ CoCreateInstance(CLSID_FilterGraph, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&graph));
+ CoCreateInstance(CLSID_CaptureGraphBuilder2, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&builder));
+ builder->SetFiltergraph(graph.Get()); graph->AddFilter(device.Get(), L"device");
+ ComPtr<IPin> pin; if (FAILED(builder->FindPin(device.Get(), PINDIR_OUTPUT, &PIN_CATEGORY_CAPTURE, &MEDIATYPE_Video, FALSE, 0, &pin))) { std::printf("PIN none\n"); return 3; }
+ ComPtr<IAMStreamConfig> config; pin.As(&config); int count = 0, size = 0; config->GetNumberOfCapabilities(&count, &size);
+ std::vector<BYTE> caps(size);
+ if (mode == "list") {
+ for (int i = 0; i < count; ++i) {
+ AM_MEDIA_TYPE* t = nullptr; if (FAILED(config->GetStreamCaps(i, &t, caps.data()))) continue;
+ LONG w = 0, h = 0; REFERENCE_TIME* iv = nullptr;
+ if (dims(t, w, h, iv)) {
+ auto* c = reinterpret_cast<VIDEO_STREAM_CONFIG_CAPS*>(caps.data());
+ std::printf("CAP %d %s %ldx%ld fps=%.2f..%.2f sample=%lu\n", i, fourccName(t->subtype).c_str(), w, h,
+ c->MaxFrameInterval ? 1e7 / double(c->MaxFrameInterval) : 0, c->MinFrameInterval ? 1e7 / double(c->MinFrameInterval) : 0, t->lSampleSize);
+ }
+ freeType(t);
+ }
+ return 0;
+ }
+ if (argc < 9) return 1;
+ const LONG wantW = atol(argv[3]), wantH = atol(argv[4]); const double fps = atof(argv[5]); const std::string fourcc = argv[6];
+ const long buffers = atol(argv[7]); const double seconds = atof(argv[8]);
+ AM_MEDIA_TYPE* chosen = nullptr;
+ for (int i = 0; i < count && !chosen; ++i) {
+ AM_MEDIA_TYPE* t = nullptr; if (FAILED(config->GetStreamCaps(i, &t, caps.data()))) continue;
+ LONG w = 0, h = 0; REFERENCE_TIME* iv = nullptr;
+ if (dims(t, w, h, iv) && w == wantW && h == wantH && (fourcc == "any" || t->subtype == fourccGuid(fourcc.c_str()))) { *iv = REFERENCE_TIME(1e7 / fps + .5); chosen = t; }
+ else freeType(t);
+ }
+ if (!chosen) { std::printf("FORMAT not offered\n"); return 4; }
+ const HRESULT setHr = config->SetFormat(chosen);
+ HRESULT suggestHr = S_FALSE;
+ if (buffers > 0) {
+ ComPtr<IAMBufferNegotiation> negotiation;
+ if (SUCCEEDED(pin.As(&negotiation))) { ALLOCATOR_PROPERTIES want{buffers, LONG(chosen->lSampleSize ? chosen->lSampleSize : -1), -1, -1}; suggestHr = negotiation->SuggestAllocatorProperties(&want); }
+ else suggestHr = E_NOINTERFACE;
+ }
+ ComPtr<IBaseFilter> grabFilter, nullFilter; ComPtr<ISampleGrabber> grab;
+ CoCreateInstance(kSampleGrabber, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&grabFilter)); grabFilter.As(&grab);
+ CoCreateInstance(kNullRenderer, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&nullFilter));
+ graph->AddFilter(grabFilter.Get(), L"grab"); graph->AddFilter(nullFilter.Get(), L"null");
+ AM_MEDIA_TYPE want{}; want.majortype = MEDIATYPE_Video; want.subtype = chosen->subtype; grab->SetMediaType(&want);
+ Grab cb; grab->SetBufferSamples(FALSE); grab->SetOneShot(FALSE); grab->SetCallback(&cb, 0);
+ ComPtr<IPin> grabIn, grabOut, nullIn;
+ builder->FindPin(grabFilter.Get(), PINDIR_INPUT, nullptr, nullptr, TRUE, 0, &grabIn);
+ builder->FindPin(grabFilter.Get(), PINDIR_OUTPUT, nullptr, nullptr, TRUE, 0, &grabOut);
+ builder->FindPin(nullFilter.Get(), PINDIR_INPUT, nullptr, nullptr, TRUE, 0, &nullIn);
+ HRESULT hr = graph->ConnectDirect(pin.Get(), grabIn.Get(), chosen);
+ if (SUCCEEDED(hr)) hr = graph->ConnectDirect(grabOut.Get(), nullIn.Get(), nullptr);
+ if (FAILED(hr)) { std::printf("CONNECT hr=0x%08lX\n", hr); return 5; }
+ ALLOCATOR_PROPERTIES actual{}; { ComPtr<IMemInputPin> mem; ComPtr<IMemAllocator> alloc; if (SUCCEEDED(grabIn.As(&mem)) && SUCCEEDED(mem->GetAllocator(&alloc))) alloc->GetProperties(&actual); }
+ ComPtr<IMediaControl> control; graph.As(&control); ComPtr<IMediaFilter> filter; graph.As(&filter);
+ graph->SetDefaultSyncSource(); filter->GetSyncSource(&cb.clock);
+ hr = control->Pause(); REFERENCE_TIME now = 0; if (cb.clock) cb.clock->GetTime(&now);
+ cb.start = now + 200000; hr = filter->Run(cb.start);
+ const double begin = nowMs(); while (nowMs() - begin < seconds * 1000) Sleep(50);
+ control->Stop();
+ std::vector<double> ages, intervals; double stampRate = 0, arrivalRate = 0, ageDrift = 0;
+ { std::lock_guard lock(cb.mutex); ages.assign(cb.ages.begin() + std::min<size_t>(30, cb.ages.size()), cb.ages.end());
+ for (size_t i = 31; i < cb.arrivals.size(); ++i) intervals.push_back(cb.arrivals[i] - cb.arrivals[i - 1]);
+ const size_t n = cb.arrivals.size();
+ if (n > 60) {
+ // Frames per second by the driver's stamps and by actual arrival: synthetic
+ // stamps (frame count x nominal interval) drift away from real arrivals.
+ stampRate = double(n - 31) * 1000.0 / (cb.streamMs[n - 1] - cb.streamMs[30]);
+ arrivalRate = double(n - 31) * 1000.0 / (cb.arrivals[n - 1] - cb.arrivals[30]);
+ ageDrift = cb.ages[n - 1] - cb.ages[30];
+ } }
+ size_t bursts = 0; for (double d : intervals) bursts += d < 4.0;
+ std::printf("RUN device=\"%ls\" %ldx%ld %s fps=%.2f setFormat=0x%08lX suggest=%ld hr=0x%08lX allocator=%ld run=0x%08lX clock=%d frames=%zu "
+ "ageP50=%.2f ageP95=%.2f ageMin=%.2f ageMax=%.2f ageDrift=%.2f stampFps=%.3f arrivalFps=%.3f intervalP50=%.2f intervalP95=%.2f intervalMax=%.2f bursts=%zu\n",
+ name.c_str(), wantW, wantH, fourccName(chosen->subtype).c_str(), fps, setHr, buffers, suggestHr, actual.cBuffers, hr, cb.clock ? 1 : 0, ages.size(),
+ pct(ages, .5), pct(ages, .95), pct(ages, 0), pct(ages, 1), ageDrift, stampRate, arrivalRate, pct(intervals, .5), pct(intervals, .95), pct(intervals, 1), bursts);
+ freeType(chosen);
+ return 0;
+}
diff --git a/src/engine/EngineController.cpp b/src/engine/EngineController.cpp
index 5e598e22..b12027f7 100644
--- a/src/engine/EngineController.cpp
+++ b/src/engine/EngineController.cpp
@@ -1104,7 +1104,9 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
// 60 fps content modes, repeated pictures (every component within the
// capture-noise band, PictureCompare.h) are dropped before any GPU work and
// kept frames get content timestamps. "60->30" is the plain
- // every-second-sample CaptureHalfRate again (user 2026-10-12).
+ // every-second-sample CaptureHalfRate again (user 2026-10-12); since
+ // 2026-10-27 the callback's picture numbers only move its phase onto the
+ // first copies of a 30 fps game (CaptureHalfRate.h).
// VEYRA_TEST_CONTENT_DEDUP_LEGACY=1 restores the report-only content modes
// for A/B runs.
ContentDedup contentDedup;uint64_t dedupRevision=0;
@@ -2003,8 +2005,8 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
const bool halfRate=isCapture&&options.settings.content==ContentRate::Capture60To30&&
CaptureHalfRate::supported(activeSource->info().averageFps);
const bool dedupActive=isCapture&&!isImage&&!legacyCadence&&dedupContent(options.settings.content);
- // The callback compares whole pictures only while dedup needs them.
- if(physicalCapture)captureSource.setPictureCompare(dedupActive);
+ // The callback compares whole pictures only while dedup or the 60->30 phase needs them.
+ if(physicalCapture)captureSource.setPictureCompare(dedupActive||halfRate);
if(reset||pipeline::breaksHistory(pkt.flags))captureSampler.reset();
const int64_t samplePts100ns=pkt.pts.isUnknown()?0:pkt.pts.to100ns();
if(dedupActive&&!rereadCached&&!pkt.pts.isUnknown()){
@@ -2027,10 +2029,18 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
if(decision.interval>0)pkt.duration={decision.interval,10000000};
}else if(halfRate&&!rereadCached){
// 60->30: every second sample by timestamp, original PTS, a steady 30.
+ // Only a number the capture callback already computed is used, so the
+ // engine thread never compares a whole picture for this.
const auto interval=liveSourceInterval100ns(pipeline::Rational::unknown(),activeSource->info().averageFps);
- if(!pkt.pts.isUnknown()&&!captureSampler.accept(pkt.pts.to100ns(),interval,false)){
+ const auto* upload=pipeline::captureUploadFrame(frame);
+ const uint64_t* picture=upload&&upload->pictureValid?&upload->pictureId:nullptr;
+ const auto shifts=captureSampler.shifts();
+ if(!pkt.pts.isUnknown()&&!captureSampler.accept(pkt.pts.to100ns(),interval,false,picture)){
std::lock_guard lock(mutex_);++snapshot_.captureRateSkipped;continue;
}
+ if(captureSampler.shifts()!=shifts||(picture&&captureSampler.gridKept()%600==0))
+ veyra::log::info("capture-rate",std::format("60->30 phase: shifts={} keptOnGrid={} secondCopiesKept={} (a 30 fps game moves onto first copies; 60 fps content never repeats)",
+ captureSampler.shifts(),captureSampler.gridKept(),captureSampler.secondCopiesKept()));
pkt.duration={interval*2,10000000};
}
if(!halfRate)captureSampler.reset();
diff --git a/tests/unit/LivePresentationTimingTests.cpp b/tests/unit/LivePresentationTimingTests.cpp
index a0775f4e..dbe84097 100644
--- a/tests/unit/LivePresentationTimingTests.cpp
+++ b/tests/unit/LivePresentationTimingTests.cpp
@@ -48,6 +48,33 @@ int main(){
check(sampler.accept(dt,dt,true),"history boundary cannot be swallowed by sampling");
sampler.reset();check(sampler.accept(dt,dt,false),"reset accepts first new frame immediately");
}
+ {
+ // Phase onto first copies (2026-10-27). picture(i) is the number of sample i.
+ const int64_t dt=166667;
+ auto run=[&](auto picture,int start,int count,std::vector<int>& kept){
+ CaptureHalfRate sampler;
+ for(int i=start;i<start+count;++i){const uint64_t id=picture(i);if(sampler.accept(i*dt+(i%3-1)*1000,dt,false,&id))kept.push_back(i);}
+ return sampler.shifts();
+ };
+ // 30 fps game: samples 2k and 2k+1 show picture k; the grid starts on a second copy.
+ std::vector<int> wrong;const auto shifts=run([](int i){return uint64_t(i/2);},1,400,wrong);
+ bool firstsAfter=true,noneLost=true;
+ for(size_t n=0;n+1<wrong.size();++n)noneLost&=wrong[n+1]/2-wrong[n]/2<=1;
+ for(size_t n=6;n<wrong.size();++n)firstsAfter&=wrong[n]%2==0;
+ check(shifts==1&&firstsAfter&&noneLost,"30 fps content moves onto first copies once and loses no picture");
+ check(wrong.size()>=199&&wrong.size()<=201,"30 fps content keeps 30 per second");
+ std::vector<int> right;
+ check(run([](int i){return uint64_t(i/2);},0,400,right)==0&&right.size()==200&&std::all_of(right.begin(),right.end(),[](int i){return i%2==0;}),
+ "first copies already: no move");
+ // 60 fps game: every sample new; the picture numbers change nothing.
+ std::vector<int> sixty;CaptureHalfRate plain;int plainKept=0;bool same=true;size_t at=0;
+ run([](int i){return uint64_t(i);},0,600,sixty);
+ for(int i=0;i<600;++i){const bool accepted=plain.accept(i*dt+(i%3-1)*1000,dt,false);plainKept+=accepted;if(accepted)same&=at<sixty.size()&&sixty[at++]==i;}
+ check(same&&size_t(plainKept)==sixty.size(),"60 fps content keeps the plain every-second-sample grid");
+ // 45 fps in 60 Hz (new,new,new,repeat): never three second copies in a row.
+ std::vector<int> fortyFive;
+ check(run([](int i){return uint64_t(i-i/4);},0,600,fortyFive)==0&&fortyFive.size()==300,"irregular content keeps the plain grid");
+ }
check(!CaptureHalfRate::supported(30)&&!CaptureHalfRate::supported(18)&&!CaptureHalfRate::supported(120)&&CaptureHalfRate::supported(59.94),"60-to-30 setting does not halve other transport modes");
veyra::engine::FrameRateWindow rate;rate.reset(0);
for(int i=1;i<=60;++i)rate.complete(i*166666);