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 named color presets and bitmap subtitles; distinguish capture input limits
Veyra Goal Agent4c41ffaacd59
diff --git a/CMakeLists.txt b/CMakeLists.txtindex bf268816..c23f4b4b 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -542,6 +542,9 @@ if(VEYRA_FFMPEG_ROOT AND EXISTS "${VEYRA_FFMPEG_ROOT}/include/libavformat/avformadd_executable(veyra_repair_contract_tests tests/unit/RepairContractTests.cpp)add_executable(veyra_subtitle_loading_tests tests/integration/SubtitleLoadingTests.cpp)+ add_executable(veyra_bitmap_subtitle_tests tests/integration/BitmapSubtitleTests.cpp)+ target_link_libraries(veyra_bitmap_subtitle_tests PRIVATE veyra_engine)+ target_compile_features(veyra_bitmap_subtitle_tests PRIVATE cxx_std_20)target_link_libraries(veyra_subtitle_loading_tests PRIVATE veyra_engine)target_compile_features(veyra_subtitle_loading_tests PRIVATE cxx_std_20)# veyra_engine is linked for the subtitle engine (SRT/ASS/VTT parsing +diff --git a/apps/veyra/SettingsWindow.cpp b/apps/veyra/SettingsWindow.cppindex 7749a9fc..7be31284 100644--- a/apps/veyra/SettingsWindow.cpp+++ b/apps/veyra/SettingsWindow.cpp@@ -234,9 +234,7 @@ void saveColourFoldState(){preferences.colourFoldMask=colorFoldMask;if(!store_.save(preferences,nullptr))veyra::log::warn("color-ui","fold state not saved");}-void layoutColorPage(){- RECT bodyRect{};GetClientRect(body,&bodyRect);- const int bodyWidthDip=MulDiv(bodyRect.right,96,veyra::ui::layoutDpi(window));+void layoutColorPage(int bodyWidthDip){auto place=[&](int id,int y,int height,bool hidden,int x=-1,int w=-2){for(auto& entry:items)if(GetDlgCtrlID(entry.h)==id){entry.y=y;entry.height=height;entry.hidden=hidden;if(x>=0)entry.x=x;if(w!=-2)entry.w=w;return;}};@@ -248,12 +246,20 @@ void layoutColorPage(){// import/export. The combo and the name field used to both stretch to the// full width and cover each other, which is why users reported "there is no// place to save a preset".- const int presetHalf=std::max(dip(window,120),(bodyWidthDip-36)/2);+ const int presetHalf=std::max(1,(bodyWidthDip-36)/2);place(803,y,30,false,12,presetHalf);place(804,y,30,false,12+presetHalf+12,presetHalf-6);y+=36;- place(805,y,32,false);place(806,y,32,false);place(807,y,32,false);place(808,y,32,false);place(809,y,32,false);y+=40;- place(801,y,32,false);place(802,y,32,false);place(824,y,32,false);place(822,y,32,false);place(823,y,32,false);y+=38;+ auto toolbar=[&](std::initializer_list<int> ids){+ const int available=std::max(1,bodyWidthDip-24);+ const int columns=std::clamp((available+6)/96,1,int(ids.size()));+ const int width=(available-6*(columns-1))/columns;+ int index=0;+ for(int id:ids){place(id,y+(index/columns)*38,32,false,12+(index%columns)*(width+6),width);++index;}+ y+=((index+columns-1)/columns)*38;+ };+ toolbar({805,806,807,808,809});+ toolbar({801,802,824,822,823});place(821,y,32,false);y+=42;for(int section=0;section<kColorSections;++section){const bool collapsed=(colorFoldMask>>section)&1u;@@ -1091,7 +1097,8 @@ LRESULT CALLBACK holdOriginalProc(HWND h,UINT msg,WPARAM wp,LPARAM lp,UINT_PTR ivoid arrange(){if(!window||!body)return;RECT r{};GetClientRect(window,&r);int width=MulDiv(r.right,96,veyra::ui::layoutDpi(window)),height=MulDiv(r.bottom,96,veyra::ui::layoutDpi(window));const int sticky=128,viewport=std::max(1,height-sticky);contentHeight=0;- if(page==2)layoutColorPage();+ // The child still has its previous size until SetWindowPos below.+ if(page==2)layoutColorPage(width);int helpHeight=0;if(smoothMotionHelpExpanded){auto dc=GetDC(window);auto old=SelectObject(dc,font);RECT textRect{0,0,dip(window,std::max(1,width-24)),0};DrawTextW(dc,smoothMotionHelp,-1,&textRect,DT_CALCRECT|DT_WORDBREAK|DT_NOPREFIX);SelectObject(dc,old);ReleaseDC(window,dc);helpHeight=MulDiv(textRect.bottom,96,layoutDpi(window))+16;}const auto helpOffset=[&](const Item& entry){const auto id=GetDlgCtrlID(entry.h);return entry.page==1&&(id==1114||id==205||id==1110||id==240||id==241||id==242||id==1150)?helpHeight:0;};@@ -1207,11 +1214,22 @@ LRESULT CALLBACK proc(HWND h,UINT msg,WPARAM wp,LPARAM lp){engine::ColorLookStore lookStore(runtime::localDataDirectory());if(id==805){wchar_t name[64]{};GetWindowTextW(item(804),name,64);+ if(std::wstring(name).find_first_not_of(L" \t\r\n")==std::wstring::npos){+ SetFocus(item(804));+ MessageBoxW(window,L"请输入预设名称,再点击保存。",L"保存色彩预设",MB_OK|MB_ICONINFORMATION);+ return 0;+ }+ if(!lookStore.load()){+ MessageBoxW(window,lookStore.error().c_str(),L"保存失败",MB_OK|MB_ICONERROR);return 0;+ }+ const bool exists=std::any_of(lookStore.entries().begin(),lookStore.entries().end(),[&](const auto& entry){return entry.name==name;});+ if(exists&&MessageBoxW(window,L"已存在同名预设,是否覆盖?",name,MB_YESNO|MB_ICONQUESTION)!=IDYES)return 0;auto colour=colourTarget();colour.enabled=true;- if(lookStore.load()&&lookStore.put(name,colour,true)){+ if(lookStore.put(name,colour,true)){refreshColourLooks(name);- message(L"已保存色彩预设(同名会覆盖)。可以导出成 .vpcolor 分享。");- }else message(L"保存失败:"+lookStore.error());+ message(L"已保存色彩预设:"+std::wstring(name));+ veyra::log::info("color-ui","named preset saved to disk and selected");+ }else MessageBoxW(window,lookStore.error().c_str(),L"保存失败",MB_OK|MB_ICONERROR);}else if(id==806){const int index=int(SendMessageW(item(803),CB_GETCURSEL,0,0));if(lookStore.load()&&index>=1&&size_t(index-1)<lookStore.entries().size()){@@ -1435,6 +1453,7 @@ case WM_CREATE:{window=h;font=makeFont(h);items.clear();displayedBackendWarning.}// Preset toolbar.combo(803,2,0,{});add(L"EDIT",L"",804,ES_AUTOHSCROLL|WS_TABSTOP,2,12,0,-1,26);send(804,EM_SETLIMITTEXT,48,0);+ send(804,EM_SETCUEBANNER,TRUE,LPARAM(L"预设名称"));button(L"保存为预设",805,2,12,0,110);button(L"应用",806,2,12,0,80);button(L"删除",807,2,12,0,80);button(L"导出",808,2,12,0,80);button(L"导入",809,2,12,0,80);SetPropW(item(804),L"veyra.tip",HANDLE(L"给当前色彩设置起个名字,点“保存预设”存下来;导出会生成 .vpcolor 文件,可以发给别人导入。"));diff --git a/apps/veyra/ui/AppShell.cpp b/apps/veyra/ui/AppShell.cppindex b2cb07aa..0306d91d 100644--- a/apps/veyra/ui/AppShell.cpp+++ b/apps/veyra/ui/AppShell.cpp@@ -377,7 +377,7 @@ for(int id:std::initializer_list<int>{Open,Capture,Recent,Master,Save,Sr,Play,Stpos(statusBar,0,0,1,1,false);pos(diagnosticPanel,g.left,g.top,g.viewWidth,h-g.top-20,!full&&pro&&showDiagnostics);const bool empty=currentFile.empty();put(EmptyTitle,0,0,1,1,false);put(EmptyHint,0,0,1,1,false);for(int id:{EmptyTitle,EmptyHint})surface(GetDlgItem(mainWindow,id),background);- pos(subtitleLabel,full?20:g.left+20,full?h-(fullControls?274:190):g.top+g.viewHeight-190,full?w-40:g.viewWidth-40,180,uiState.subtitles&&GetWindowTextLengthW(subtitleLabel)>0);+ pos(subtitleLabel,full?0:g.left,full?0:g.top,full?w:g.viewWidth,full?h:g.viewHeight,uiState.subtitles&&GetWindowTextLengthW(subtitleLabel)>0);put(JobProgress,tx,barTop+10,std::min(300,tw),24,exportJob.poll().state!=veyra::engine::ExportState::Idle&&!full);// Each HWND enters the batch once. Mixing HIDE/SHOW entries for a child// causes DeferWindowPos to preserve the earlier hide flag on Windows.@@ -697,6 +697,7 @@ if(smokeStep==4&&elapsed>5200&&GetEnvironmentVariableW(L"VEYRA_TEST_LARGE_IMAGE_for(const auto* cue:veyra::engine::cuesAt(track,position,3)){veyra::ui::SubtitleLine line;line.text=cue->text;+ line.bitmap=cue->bitmap;line.style=track.styles.empty()?veyra::engine::SubtitleStyle{}:track.styles[size_t(std::clamp(cue->style,0,int(track.styles.size())-1))];if(cue->alignOverride)line.style.alignment=cue->alignOverride;line.alignOverride=cue->alignOverride;@@ -716,6 +717,10 @@ if(smokeStep==4&&elapsed>5200&&GetEnvironmentVariableW(L"VEYRA_TEST_LARGE_IMAGE_view.outline=uiState.subtitleOutline;view.background=uiState.subtitleBackground;view.bottomMargin=uiState.subtitleMargin;+ if(full&&fullControls)view.bottomMargin+=84;+ view.preview=engine.previewView();+ view.videoWidth=s.metrics.resolution.output.width;+ view.videoHeight=s.metrics.resolution.output.height;veyra::ui::updateSubtitleOverlay(subtitleLabel,draw,view);static std::wstring lastSubtitleLog;if(!draw.empty()){@@ -890,6 +895,15 @@ else if(colorStep==47){// Named colour presets: save the current look, clear a value, apply the preset,// then delete it - the same three actions the panel exposes.else if(colorStep==52){+ veyra::ui::settingsColorScrollToTest(805);+ bool hit=true;+ for(int id:{805,806,807,808,809}){+ const auto control=colourControl(id);RECT rect{};GetWindowRect(control,&rect);+ POINT point{(rect.left+rect.right)/2,(rect.top+rect.bottom)/2};ScreenToClient(GetParent(control),&point);+ hit&=ChildWindowFromPointEx(GetParent(control),point,CWP_SKIPINVISIBLE|CWP_SKIPDISABLED)==control;+ }+ veyra::log::info("color-ui-test",std::format("preset toolbar buttons reachable={}",hit));+ if(!hit){colorStep=-1;return 0;}if(auto edit=colourControl(804))SetWindowTextW(edit,L"烟测预设");SendMessageW(colourControl(805),BM_CLICK,0,0);colorStep=53;diff --git a/apps/veyra/ui/LiveStatusDashboard.h b/apps/veyra/ui/LiveStatusDashboard.hindex 43d9c76f..8a3de089 100644--- a/apps/veyra/ui/LiveStatusDashboard.h+++ b/apps/veyra/ui/LiveStatusDashboard.h@@ -1,24 +1,9 @@#pragma once#include <deque>#include <optional>+#include "LiveStatusHistory.h"namespace veyra::ui::live_status {-struct DashboardHistory {- std::deque<std::optional<double>> points;- uint64_t session=0,revision=0;unsigned low=0,good=0;bool overloaded=false;- void sample(const engine::PlayerSnapshot& s){- if(session!=s.sessionId||revision!=s.applied.revision){points.clear();low=good=0;overloaded=false;session=s.sessionId;revision=s.applied.revision;}- const bool active=s.running&&!s.image&&s.transport==engine::TransportState::Playing&&!s.applying;- auto value=active?s.metrics.flow.enhancementProcessing.mean:std::optional<double>{};- points.push_back(value);if(points.size()>120)points.pop_front();- const bool xess=s.applied.multiplier>1&&engine::presentSinkFrameGeneration(s.applied.frameGenerationBackend);- const double actual=xess?s.metrics.flow.xessSdkSubmitFps:s.metrics.flow.presentSubmitFps;- const double target=s.nominalSourceFps*(s.captureHalfRate?.5:1)*s.applied.multiplier;- if(!active||!s.metrics.flow.rateWindowReady||target<=0){low=good=0;overloaded=false;return;}- if(actual<target*.95){good=0;if(++low>=8)overloaded=true;}- else{low=0;if(++good>=8)overloaded=false;}- }-};inline void paintDashboard(HWND h,HDC dc,int w,int height,const engine::PlayerSnapshot& s,const DashboardHistory& history,bool advanced=false){const auto& f=s.metrics.flow;const bool active=s.running&&!s.image&&s.transport==engine::TransportState::Playing;auto text=[&](std::wstring str,int x,int y,int width,int ht,int size,COLORREF color){chromeText(dc,h,str,x,y,width,ht,size,color);};@@ -69,11 +54,11 @@ inline void paintDashboard(HWND h,HDC dc,int w,int height,const engine::PlayerSnstd::wstring status=L"待机";COLORREF color=RGB(145,151,149);if(s.failed){status=L"错误";color=RGB(245,86,86);}else if(s.remoteRecovering){status=L"恢复中";color=RGB(242,185,65);}- else if(active&&!s.applying&&f.rateWindowReady){status=history.overloaded?(s.applied.multiplier>1?L"补帧受限":L"处理过载"):L"正常";color=history.overloaded?RGB(242,185,65):RGB(111,211,127);}+ else if(active&&!s.applying&&f.rateWindowReady){status=history.rateStatus(s);color=status!=L"正常"?RGB(242,185,65):RGB(111,211,127);}else if(s.applying&&s.running)status=L"调整中";else if(active)status=L"采样中";else if(s.transport==engine::TransportState::Paused)status=L"已暂停";text(L"当前状态",26+bw,bottom+6,bw-20,18,10,secondary);{AlphaGraphics draw(dc);Gdiplus::SolidBrush dot(Gdiplus::Color(255,GetRValue(color),GetGValue(color),GetBValue(color)));draw.get().FillEllipse(&dot,dip(h,27+bw),dip(h,bottom+35),dip(h,8),dip(h,8));}- text(status,42+bw,bottom+27,bw-38,23,16,textColor);+ text(status,42+bw,bottom+27,bw-38,23,status.size()>5?11:16,textColor);text(xess?L"* 帧生成耗时为应用侧计时,不含提供方内部插值":L"增强阶段GPU计时 · 不含音频和呈现等待",12,height-18,w-24,16,8,secondary);}}diff --git a/apps/veyra/ui/LiveStatusHistory.h b/apps/veyra/ui/LiveStatusHistory.hnew file mode 100644index 00000000..fa1b30fa--- /dev/null+++ b/apps/veyra/ui/LiveStatusHistory.h@@ -0,0 +1,43 @@+#pragma once+#include "veyra/engine/EngineController.h"+#include <deque>+#include <optional>++namespace veyra::ui::live_status {+struct DashboardHistory {+ std::deque<std::optional<double>> points;+ uint64_t session=0,revision=0,epoch=0;+ unsigned low=0,good=0,inputLow=0,resetSamples=0;+ bool overloaded=false,inputLimited=false;+ void sample(const engine::PlayerSnapshot& s){+ if(session!=s.sessionId||revision!=s.applied.revision){+ points.clear();low=good=inputLow=resetSamples=0;epoch=0;+ overloaded=inputLimited=false;session=s.sessionId;revision=s.applied.revision;+ }+ const bool active=s.running&&!s.image&&s.transport==engine::TransportState::Playing&&!s.applying;+ points.push_back(active?s.metrics.flow.enhancementProcessing.mean:std::optional<double>{});+ if(points.size()>120)points.pop_front();+ const auto nextEpoch=s.metrics.flow.reset.epoch;+ if(active&&epoch&&nextEpoch>epoch+1)resetSamples=std::min(resetSamples+1,8u);+ else if(resetSamples) --resetSamples;+ epoch=nextEpoch;+ const bool measuredInput=s.capture&&s.captureReceived>30&&s.captureFps>0;+ const double source=measuredInput?std::min(s.nominalSourceFps,s.captureFps):s.nominalSourceFps;+ if(active&&measuredInput&&s.captureFps<s.nominalSourceFps*.95)inputLow=std::min(inputLow+1,8u);+ else inputLow=0;+ inputLimited=inputLow>=8;+ const bool xess=s.applied.multiplier>1&&engine::presentSinkFrameGeneration(s.applied.frameGenerationBackend);+ const double actual=xess?s.metrics.flow.xessSdkSubmitFps:s.metrics.flow.presentSubmitFps;+ const double target=source*(s.captureHalfRate?.5:1)*s.applied.multiplier;+ if(!active||!s.metrics.flow.rateWindowReady||target<=0){low=good=0;overloaded=false;return;}+ if(actual<target*.95){good=0;if(++low>=8)overloaded=true;}+ else{low=0;if(++good>=8)overloaded=false;}+ }+ const wchar_t* rateStatus(const engine::PlayerSnapshot& s)const{+ if(resetSamples>=3)return L"输入时间线异常";+ if(inputLimited)return L"输入帧率不足";+ if(s.applied.multiplier>1&&(s.fgBudgetLimited||s.xessGenerationSuppressed))return L"补帧调度降档";+ return overloaded?L"输出未达标":L"正常";+ }+};+}diff --git a/apps/veyra/ui/SubtitleOverlay.cpp b/apps/veyra/ui/SubtitleOverlay.cppindex dac7e69b..36964391 100644--- a/apps/veyra/ui/SubtitleOverlay.cpp+++ b/apps/veyra/ui/SubtitleOverlay.cpp@@ -34,9 +34,11 @@ std::wstring signatureOf(const std::vector<SubtitleLine>& lines,const SubtitleVifor(const auto& line:lines){signature+=std::format(L"{}|{:08X}|{:08X}|{}|{:.1f}|{}|{}|{}|",line.text,line.style.primary,line.style.outline,line.style.font,line.style.size,line.style.alignment,line.alignOverride,line.secondary?1:0);+ signature+=std::format(L"{}:{:.4f}:{:.4f}|",reinterpret_cast<uintptr_t>(line.bitmap.get()),line.posX,line.posY);}signature+=std::format(L"#{:.2f}|{}|{}|{}|{}|{}",view.scale,view.fontOverride,view.outline?1:0,view.background?1:0,view.bottomMargin,view.blockGap);signature+=std::format(L"/{}x{}",rect.right,rect.bottom);+ signature+=std::format(L"/{}/{}/{}/{}/{}",view.preview.zoom,view.preview.centerX,view.preview.centerY,view.videoWidth,view.videoHeight);return signature;}@@ -56,9 +58,12 @@ HWND createSubtitleOverlay(HWND parent){void updateSubtitleOverlay(HWND h,const std::vector<SubtitleLine>& lines,const SubtitleView& view){RECT rect{};GetClientRect(h,&rect);- if(lines.empty()||rect.right<1||rect.bottom<1){ShowWindow(h,SW_HIDE);SetWindowTextW(h,L"");return;}- const auto signature=signatureOf(lines,view,rect);static thread_local std::wstring lastSignature;+ static thread_local HWND lastWindow=nullptr;+ static thread_local std::vector<std::shared_ptr<const engine::SubtitleBitmapFrame>> lastBitmaps;+ if(h!=lastWindow){lastSignature.clear();lastBitmaps.clear();lastWindow=h;}+ if(lines.empty()||rect.right<1||rect.bottom<1){lastSignature.clear();lastBitmaps.clear();ShowWindow(h,SW_HIDE);SetWindowTextW(h,L"");return;}+ const auto signature=signatureOf(lines,view,rect);if(lastSignature==signature){ShowWindow(h,SW_SHOWNOACTIVATE);return;}const int width=rect.right,height=rect.bottom;BITMAPINFO info{};info.bmiHeader.biSize=sizeof(BITMAPINFOHEADER);info.bmiHeader.biWidth=width;info.bmiHeader.biHeight=-height;@@ -80,6 +85,22 @@ void updateSubtitleOverlay(HWND h,const std::vector<SubtitleLine>& lines,const Sstd::vector<Line> laid;laid.reserve(lines.size());for(const auto& line:lines){+ if(line.bitmap){+ const auto& frame=*line.bitmap;+ const double vw=view.videoWidth>0?view.videoWidth:frame.width,vh=view.videoHeight>0?view.videoHeight:frame.height;+ if(frame.width<=0||frame.height<=0||vw<=0||vh<=0)continue;+ const double fit=std::min(width/vw,height/vh)*view.preview.zoom;+ const double sx=vw*fit/frame.width,sy=vh*fit/frame.height;+ const double ox=width*.5-view.preview.centerX*vw*fit,oy=height*.5-view.preview.centerY*vh*fit;+ graphics.SetInterpolationMode(InterpolationModeHighQualityBilinear);+ for(const auto& image:frame.images){+ auto pixels=image.pixels();if(pixels.empty())continue;+ Bitmap source(image.width,image.height,image.width*4,PixelFormat32bppPARGB,reinterpret_cast<BYTE*>(pixels.data()));+ graphics.DrawImage(&source,RectF(float(ox+image.x*sx),float(oy+image.y*sy),float(image.width*sx),float(image.height*sy)),0,0,float(image.width),float(image.height),UnitPixel);+ }+ continue;+ }+ if(line.text.empty())continue;Line entry;entry.path=std::make_unique<Gdiplus::GraphicsPath>();entry.style=line.style;@@ -161,9 +182,13 @@ void updateSubtitleOverlay(HWND h,const std::vector<SubtitleLine>& lines,const Sgraphics.FillPath(&fill,entry.path.get());}lastSignature=signature;+ // Retain the identities used by the cache until its signature changes.+ lastBitmaps.clear();+ for(const auto& line:lines)if(line.bitmap)lastBitmaps.push_back(line.bitmap);}SIZE dimensions{width,height};POINT origin{};BLENDFUNCTION blend{AC_SRC_OVER,0,255,AC_SRC_ALPHA};if(UpdateLayeredWindow(h,screen,nullptr,&dimensions,memory,&origin,0,&blend,ULW_ALPHA)){+ SetWindowTextW(h,L"subtitle");ShowWindow(h,SW_SHOWNOACTIVATE);if(!GetPropW(h,L"subtitle.logged")){log::info("subtitle",std::format("layered update succeeded extent={}x{} lines={}",width,height,lines.size()));diff --git a/apps/veyra/ui/SubtitleOverlay.h b/apps/veyra/ui/SubtitleOverlay.hindex 6db3ac5e..96530d9a 100644--- a/apps/veyra/ui/SubtitleOverlay.h+++ b/apps/veyra/ui/SubtitleOverlay.h@@ -10,6 +10,7 @@#include <vector>#include "veyra/engine/Subtitles.h"+#include "veyra/engine/PreviewView.h"namespace veyra::ui {struct SubtitleLine {@@ -18,6 +19,7 @@ struct SubtitleLine {int alignOverride=0; // {\anN}, 0 = style alignmentdouble posX=-1,posY=-1; // {\pos(x,y)} normalised to 0..1 (or -1)bool secondary=false;+ std::shared_ptr<const engine::SubtitleBitmapFrame> bitmap;};struct SubtitleView {double scale=1.0; // viewer size multiplier@@ -26,6 +28,8 @@ struct SubtitleView {bool background=false;int bottomMargin=0; // extra logical pixels above the barint blockGap=6; // gap between the two languages+ engine::PreviewView preview;+ double videoWidth=0,videoHeight=0;};HWND createSubtitleOverlay(HWND parent);void updateSubtitleOverlay(HWND,const std::vector<SubtitleLine>&,const SubtitleView&);diff --git a/docs/5060_PRESETS_BITMAP_PLAN_2026-09-18.md b/docs/5060_PRESETS_BITMAP_PLAN_2026-09-18.mdnew file mode 100644index 00000000..93bf4e73--- /dev/null+++ b/docs/5060_PRESETS_BITMAP_PLAN_2026-09-18.md@@ -0,0 +1,92 @@+# 5060、命名调色预设与图形字幕修复++## 基线与范围++- 用户授权本地修复、构建验收、报告后关机;不发布、不推送。+- 基线 `050811b`,存档 `checkpoint/pre-5060-presets-subtitles-20260918`。+- 隔离分支 `codex/5060-presets-subtitles-20260918`,工作区沿用 `E:/项目/Veyra/worktrees/frame-pacing-20260918`。+- 构建沿用 `E:/项目/Veyra/build/frame-pacing-20260918`;新增证据、日志、临时文件分别放 `E:/项目/Veyra/{tests,logs,tmp}/5060-presets-subtitles-20260918`。++## 实施与验收++1. 对照5060完整日志与UI能力/状态流,修复有证据的开启或状态问题;不以GPU占用反推限帧原因。本机5070测试不冒充5060验收。+2. 调色保存入口提供命名、重名处理、失败反馈,验证磁盘持久化与重新加载。+3. 复用FFmpeg图形字幕解码器和现有FG后字幕层,支持位置、透明度、时间、清屏与切换,缓存有界;验证真实解码及显示,不把文字转换冒充图形字幕。+4. 构建相关目标,运行针对性单测、集成测试与实际GPU/界面验证。记录失败、未验证范围与可用构建。++## 实施结果(2026-09-19 本地时间)++### 5060:修正误分类,保留尚未确定的原因++用户日志 `C:/Users/123/Desktop/5060补帧受限,显卡占用百分之5.log` 中两个处理图均 `sr=0 nr=0 fg=0 nvof=0`,生成数为零,没有 NGX 初始化失败或用户启用效果的记录。因此不能声称该日志证明了 DLSS 在 5060 上调用失败,也不能把低占用等同于显卡算力不足。++2560x1440 YUY2 会话标称60fps、实际约40fps,出现逐帧 `PtsDiscontinuity`(reason10)重置;1920x1080 会话实际约60fps。25ms间隔未超过现有41.67ms断点阈值,旧日志不足以区分设备 discontinuity 标记与原始时间戳异常。没有擅自忽略驱动标记、伪造连续时间戳或取消真实历史 reset。++- 状态面板按实际采集速率计算输出目标,区分“输入帧率不足”“输入时间线异常”“补帧调度降档”“输出未达标”;关闭FG时不报补帧降档。40fps输入输出160fps的4X不再因未达标称240fps而误判FG受限。+- 新增限频 `capture-discontinuity` 日志,包含 driverFlag、clockBreak、原始PTS、回调间隔与样本时间,供该用户复测定位。+- 基线已有仅开补帧自动打开总增强/光流的修复,本次真实UI回归确认 DLSS/XeSS 单独选择均能生成帧、NR未执行;不将基线修复重复算作本次新增。+- **5060 实卡根因仍未完全确定,未宣称已经根治。** 下一步唯一远端任务:该用户在此构建明确选择DLSS4X后复现并回传新日志;核对设置事务与新增时间线原因,再决定设备兼容处理。本机5070结果不代替5060/616.92验收。++### 命名调色预设++根因是保存/应用/删除/导出/导入五个按钮重叠在同一位置;实测又发现调整窗口大小时布局读取旧面板宽度,窄窗口按钮会落到可视区外。++已修复两组工具栏的分列换行与当前宽度布局,名称框有“预设名称”占位。保存要求名称非空,同名确认覆盖,失败弹出明确原因,成功更新选中项和状态。入口:专业模式 → 调色 → 填名称 → 保存为预设。保存至当前应用本地数据目录的 `color-looks.v1`;本机构建为 `E:/项目/Veyra/build/frame-pacing-20260918/runtime_local/color-looks.v1`。++### 图形字幕++复用现有FFmpeg的PGS/DVD/DVB解码器,支持MKV内嵌位图字幕;保留作者画布、多个矩形、调色板、透明度、起止时间及清屏事件。在现有FG后的字幕层显示,随视频区域缩放和平移;字幕菜单沿用主/副轨选择。++缓存采用索引色游程数据与共享不可变图像,沿用异步渐进加载;正常视频处理未新增GPU像素回读。未重编译/替换FFmpeg,PS5 H.264 slice补丁和dav1d依赖保持。++边界:缓存上限仍为全文件64MiB/12万cue,达到上限会在轨道注记中报告后续未加载;多图形语言的长片需要后续按需缓存改造,不能保证任意数量轨道整片都容纳。位图不能通过字体/字号设置重新排字,不新增OCR或导出烧录字幕。未用用户真实PGS长片验收,已用有效封装样本验证三种解码器。++## 实际验收++| 检查 | 结果 |+| --- | --- |+| Release构建、UI合同、ColorLookStore、LiveTiming、RepairContract | 通过;命名保存、原子写入、损坏文件保护、状态误分类回归均通过 |+| 调色UI烟测 | 保存、应用恢复实际参数、删除通过 |+| 跨进程界面操作 | 1180/900像素宽按钮命中、中文名称保存、真正退出重启后找回通过 |+| PGS/DVD/DVB解码集成 | 三者通过;时间、清屏、随机/后退查找、位置、透明度等检查 |+| 图形字幕实际窗口 | 像素差分验证窗口/缩放/全屏两个作者位置、开关、定时清屏通过;截图留存 |+| Money Heist 文本回归 | 32轨均可用、15720cue;异步渐进结果可用,完整扫描约10.1秒,不等同首帧等待时间 |+| RTX5070 DLSS2X/4X/6X | 各15秒,实际原帧增量358/358/360、生成增量358/1074/1800,零预览跳帧;媒体速度约0.996,干净退出 |+| 冷启动只开FG界面 | DLSS和XeSS均实际光流/生成成功,NR未执行 |+| VC-007PRO 4K30 NV12 + NR实时1080 + DLSS4X | 10秒预热后15秒测量,449输入、1347生成、零采集丢帧,正常退出 |++GPU证据:RTX5070/616.56,DLSS `Create result=0x1 (NVSDK_NGX_Result_Success), handle=non-null, seh=0`;Evaluate真实计数和逐帧日志见各 `engine.log`。显示器100Hz,以上为应用生成/提交数,不是物理屏幕刷新数。++失败记录:初版PGS封装缺 `-copyts`、转DVD/DVB缺 `-fix_sub_duration`,导致测试样本时间改变,修正后通过。跨进程编辑测试用 `SetWindowTextW` 未写入文本,改用系统封送 `WM_SETTEXT` 后通过。首轮采集 `Run hr=0x800705AA`、零输入(FAIL,证据保留);正常关闭原先运行的旧版Veyra窗口后,同参数复测通过,符合资源占用冲突,未把该轮失败冒充通过。++未运行无关全量旧delivery脚本(其固定媒体/产物路径仍为旧布局);本次运行以上针对性构建、CPU、GPU、界面及采集回归。未做长时稳定性、真实5060、30/40系列或远端卡顿复现验收。++## 命令与证据++工作目录为隔离源码,所有子进程TEMP/TMP设为本任务tmp目录。实际执行的命令形式如下,转码与测试日志均保留:++```powershell+./scripts/build-isolated.ps1 -Root . -BuildDirectory 'E:/项目/Veyra/build/frame-pacing-20260918' -DependencyCache 'E:/项目/Veyra/build/frame-pacing-20260918/CMakeCache.txt' -TempDirectory 'E:/项目/Veyra/tmp/5060-presets-subtitles-20260918' -DisplayVersion 1.4.2beta -Targets veyra,veyra_color_look_tests,veyra_subtitle_loading_tests,veyra_bitmap_subtitle_tests,veyra_live_timing_tests,veyra_repair_contract_tests,veyra_ui_contract_tests+# 后续布局修复另构建 veyra,veyra_bitmap_subtitle_tests,veyra_presentation_pacing_tests+python scripts/tests/make-bitmap-subtitle-fixture.py E:/项目/Veyra/tests/5060-presets-subtitles-20260918/bitmap.sup+ffmpeg -hide_banner -y -copyts -f lavfi -i 'testsrc2=size=1280x720:rate=30:duration=9' -i bitmap.sup -map 0:v -map 1:s -c:v libx264 -preset ultrafast -crf 28 -c:s copy bitmap.mkv+ffmpeg -hide_banner -y -copyts -fix_sub_duration -i bitmap.mkv -map 0 -c:v copy -c:s dvdsub bitmap-dvd.mkv+# dvbsub 同上,实际输入/输出均为本任务 tests 下绝对路径+veyra_bitmap_subtitle_tests.exe <bitmap/bitmap-dvd/bitmap-dvb.mkv>+veyra_subtitle_loading_tests.exe 'C:/Users/123/Desktop/Money.Heist.2019.S03E02.V2.1080p.NF.WEB-DL.H264.DDP5.1-LeagueNF.mkv'+veyra_ui_contract_tests.exe <本任务独立测试目录>+veyra_color_look_tests.exe <本任务独立测试目录>+veyra_live_timing_tests.exe+veyra_repair_contract_tests.exe+veyra.exe <visible-scene.mkv> --smoke-color --smoke-seconds 30+python scripts/acceptance/ui-bitmap-presets.py E:/项目/Veyra/build/frame-pacing-20260918 E:/项目/Veyra/tests/5060-presets-subtitles-20260918/ui E:/项目/Veyra/tests/5060-presets-subtitles-20260918/bitmap.mkv+veyra_presentation_pacing_tests.exe E:/项目/Veyra/tests/1.4.2beta/visible-scene.mkv <dlss2/4/6证据目录> -1 0 <2/4/6> 15 normal+veyra.exe E:/项目/Veyra/tests/1.4.2beta/visible-scene.mkv --smoke-fg-only --smoke-seconds 30+veyra_presentation_pacing_tests.exe capture <capture4-retry证据目录> -1 0 4 15 capture-nr+```++- 可运行构建:`E:/项目/Veyra/build/frame-pacing-20260918/veyra.exe`,本机运行库引用保留;不是新的便携发布包。+- EXE SHA256:`05EB267EEE624538E02A8C452F4EA1D5B804DD884FCD1CD09B838F8E77BFED4E`。+- 构建/CPU/UI结果:`E:/项目/Veyra/logs/5060-presets-subtitles-20260918`。+- GPU日志/CSV、位图样本、界面截图及 `ui/result.json`:`E:/项目/Veyra/tests/5060-presets-subtitles-20260918`。+- 仅清理本任务无效转码中间文件;保留可用构建、有效样本、失败与成功证据。未修改用户源日志/电影文件,没有新包、合并main、推送或发布。diff --git a/docs/CURRENT_STATUS.md b/docs/CURRENT_STATUS.mdindex 5e56e483..218e3878 100644--- a/docs/CURRENT_STATUS.md+++ b/docs/CURRENT_STATUS.md@@ -16,6 +16,8 @@## 本轮开发+新增本地修复(2026-09-19):[5060、命名调色预设与图形字幕报告](5060_PRESETS_BITMAP_PLAN_2026-09-18.md)。从 `050811b` 存档后在 `codex/5060-presets-subtitles-20260918` 隔离完成预设按钮重叠/窄窗口布局、命名保存反馈、PGS/DVD/DVB图形字幕显示及状态误分类修正;CPU、实际UI、5070 DLSS2/4/6X和VC-007PRO NR+DLSS4X短测通过。5060日志实际效果全关且输入时间线反复重置,新增原因诊断,**尚未根治或通过该用户实卡验收**。保留可运行构建 `E:/项目/Veyra/build/frame-pacing-20260918/veyra.exe`,未打新包、合并main、推送或发布。+VC-007PRO 1440p60 / 4K30、NR实时+DLSS4X 的同构建对照已完成,各120秒中位软件延迟25.36/40.09ms。追加20秒逐帧短测:原帧观察就绪后等待呈现15.92/29.65ms;2K60自动/最小/驱动默认均实际分配10个allocator缓冲,没有测得缓冲选项带来的有效差异。详见[1440p60与设备缓冲实测](CAPTURE_1440P60_COMPARISON_2026-09-18.md),非HDMI到屏幕端延迟,未修改产品调度。帧同步已在隔离分支 `codex/frame-pacing-20260918` 实现并完成本机短测,基线存档 `6e69eeb`。入口:专业模式 → 运动 → 帧同步,默认关闭;低排队、均匀呈现、Reflex 实验和独立显示同步偏好可保存。无补帧文件测试减少了一帧提前缓存驻留;6X 提交吞吐保持 144fps,未证明显著降延迟或更平滑。Reflex 无补帧时真实调用 NVAPI,开启补帧时明确回退低排队并保留倍率;XeSS 继续由提供方调度。VC-007PRO 4K30 NV12、NR+DLSS4X 已完成四模式各 120 秒实卡测试,详见[采集阶段计时](CAPTURE_LATENCY_DLSS4X_2026-09-18.md)。屏幕端到端延迟、30/40 实卡、PS5、VRR 未验证,完整原计划尚未全部验收。其他验收见[帧同步报告](FRAME_PACING_ACCEPTANCE_2026-09-18.md)。未合并 main、推送、发布或更新现有 1.4.2beta 包。diff --git a/docs/WORKLOG.md b/docs/WORKLOG.mdindex dfcc8853..a1e693f1 100644--- a/docs/WORKLOG.md+++ b/docs/WORKLOG.md@@ -1,5 +1,19 @@# Veyra 工作记录+## 2026-09-19 5060分类、命名预设与图形字幕本地交付++隔离分支 `codex/5060-presets-subtitles-20260918`,基线/开工存档不变。完整范围、实际命令、证据与未完成的5060根因见 [本轮报告](5060_PRESETS_BITMAP_PLAN_2026-09-18.md)。修复调色预设五按钮重叠、窄窗口读取旧宽度、名称保存/重名确认/错误反馈;接入现有FFmpeg PGS/DVD/DVB解码与FG后透明字幕层;状态分开输入不足、时间线异常、FG调度降档和实际输出不足,新增限频采集时间戳诊断。没有改变真实驱动断点reset策略。++构建与针对性CPU测试通过,实际UI中文命名保存/进程重启、位图字幕窗口/缩放/全屏/清屏通过;32语言文本字幕回归通过。本机5070 DLSS2/4/6各15秒实际生成358/1074/1800帧,零预览跳帧,Create=0x1、seh=0;冷UI独立选择DLSS/XeSS真实光流/补帧通过。VC-007PRO 4K30 NV12、NR实时1080+DLSS4X预热10秒后15秒449输入/1347生成/零采集丢帧。首轮采集Run=0x800705AA失败,正常关闭既有旧版窗口后复测通过,未强杀用户程序。样本转码时间戳和跨进程测试输入的问题已修正,失败过程如实留在报告。++产物继续为 `E:/项目/Veyra/build/frame-pacing-20260918` 及 `E:/项目/Veyra/{tests,logs,tmp}/5060-presets-subtitles-20260918`,没有源码内生成构建/媒体或新增运行库。保留真实日志、截图、CSV、有效字幕样本及可用构建,清理本任务无效DVB中间文件。原源码main干净,未合并、推送、打包或发布。用户授权报告后关机;关机请求在最终存档后执行。++下一项:5060用户使用此构建选择DLSS4X后回传复现日志,区分设置未应用与驱动标记/PTS问题。当前仅修正有证据的状态误报,不能宣称5060卡顿或补帧受限已彻底解决;多图形轨长片受64MiB全文件缓存上限约束,未验证用户真实PGS长片。++## 2026-09-18 5060、调色预设、图形字幕开工++已在干净的 `050811b` 创建存档 `checkpoint/pre-5060-presets-subtitles-20260918` 并切换隔离分支 `codex/5060-presets-subtitles-20260918`。开工前更新 CURRENT_STATUS 与对应施工计划。新增产物根为 `E:/项目/Veyra/{tests,logs,tmp}/5060-presets-subtitles-20260918`,构建沿用 `E:/项目/Veyra/build/frame-pacing-20260918`。用户授权验收报告后关机,不推送或发布。5060日志目前只见关闭效果的两次会话,原因待进一步核对。+## 2026-09-18 1440p60 对照与设备缓冲短测用户要求 2K60 对比 4K 链路,随后追加原帧就绪后等待呈现及设备缓冲对照,仅短测。沿用隔离分支 `codex/frame-pacing-20260918`,产品基线 `88ed81c`;只修改采集对比测试入口、包装脚本与分析脚本,未改产品调度。增加精确 NV12 档位、实际回调帧率校验、缓冲策略、既有逐帧日志开关、测量窗口标记与原帧分段分析。diff --git a/include/veyra/engine/Subtitles.h b/include/veyra/engine/Subtitles.hindex bc7c5a76..b4f41f5a 100644--- a/include/veyra/engine/Subtitles.h+++ b/include/veyra/engine/Subtitles.h@@ -1,16 +1,15 @@#pragma once// Subtitle engine: external text formats (SRT/ASS/SSA/WebVTT), subtitle tracks-// embedded in the media container (text codecs only: SubRip/ASS/SSA/mov_text/-// WebVTT) and the timing helpers the UI needs. Image subtitles (PGS/DVB) have-// no decoder in the shipped FFmpeg build, so those tracks are listed with an-// explicit note instead of silently disappearing.+// embedded in the media container, including FFmpeg-decoded PGS/DVD/DVB images.#include <string>#include <vector>#include <functional>#include <memory>#include <optional>#include <stop_token>+#include <array>+#include <cstdint>namespace veyra::engine {@@ -29,12 +28,23 @@ struct SubtitleStyle {bool bold=false,italic=false,background=false;};+struct SubtitleBitmap {+ int x=0,y=0,width=0,height=0;+ std::array<uint32_t,256> palette{}; // premultiplied ARGB+ std::vector<uint32_t> runs; // upper 24 bits = count, low 8 = palette index+ std::vector<uint32_t> pixels()const;+};+struct SubtitleBitmapFrame {+ int width=0,height=0; // authored display canvas+ std::vector<SubtitleBitmap> images;+};struct SubtitleCue {double begin=0,end=0;std::wstring text; // '\n' separated, override tags already removedint style=0; // index into SubtitleTrack::stylesint alignOverride=0; // 1..9 from {\anN}; 0 = keep the style valuedouble posX=-1,posY=-1; // {\pos(x,y)} in script pixels; -1 = unset+ std::shared_ptr<const SubtitleBitmapFrame> bitmap;};struct SubtitleTrack {@@ -53,7 +63,7 @@ struct SubtitleTrack {// Format is chosen from the file extension first, then sniffed from content.SubtitleTrack loadSubtitleFile(const std::wstring& path);-// Text subtitle tracks inside the container (Matroska/MP4/...).+// Subtitle tracks inside the container (Matroska/MP4/...).std::vector<SubtitleTrack> loadEmbeddedSubtitleTracks(const std::wstring& path,std::stop_token stop={},const std::function<void(const std::vector<SubtitleTrack>&)>& metadata={});diff --git a/scripts/acceptance/ui-bitmap-presets.py b/scripts/acceptance/ui-bitmap-presets.pynew file mode 100644index 00000000..52bf5e5b--- /dev/null+++ b/scripts/acceptance/ui-bitmap-presets.py@@ -0,0 +1,198 @@+"""Own-process UI acceptance for authored bitmap positions and named presets."""+import ctypes as c+import ctypes.wintypes as w+import json+import os+import pathlib+import subprocess+import sys+import time+from PIL import ImageGrab, ImageChops++build, out, media = (pathlib.Path(p).resolve() for p in sys.argv[1:4])+assert build.name == 'frame-pacing-20260918'+out.mkdir(parents=True, exist_ok=True)+u = c.WinDLL('user32', use_last_error=True)+u.SetProcessDpiAwarenessContext.argtypes = [w.HANDLE]+u.SetProcessDpiAwarenessContext(c.c_void_p(-4))+for name, args, result in [+ ('GetWindowThreadProcessId', [w.HWND, c.POINTER(w.DWORD)], w.DWORD),+ ('GetClassNameW', [w.HWND, w.LPWSTR, c.c_int], c.c_int),+ ('GetDlgItem', [w.HWND, c.c_int], w.HWND),+ ('GetWindowRect', [w.HWND, c.POINTER(w.RECT)], w.BOOL),+ ('IsWindowVisible', [w.HWND], w.BOOL),+ ('SetWindowTextW', [w.HWND, w.LPCWSTR], w.BOOL),+ ('SetForegroundWindow', [w.HWND], w.BOOL),+ ('SetWindowPos', [w.HWND, w.HWND, c.c_int, c.c_int, c.c_int, c.c_int, w.UINT], w.BOOL),+ ('ChildWindowFromPointEx', [w.HWND, w.POINT, w.UINT], w.HWND),+ ('ScreenToClient', [w.HWND, c.POINTER(w.POINT)], w.BOOL),+ ('SendMessageTimeoutW', [w.HWND, w.UINT, w.WPARAM, w.LPARAM, w.UINT, w.UINT, c.POINTER(c.c_size_t)], w.LPARAM),+]:+ fn = getattr(u, name); fn.argtypes = args; fn.restype = result+callback = c.WINFUNCTYPE(w.BOOL, w.HWND, w.LPARAM)+u.EnumWindows.argtypes = [callback, w.LPARAM]+u.EnumChildWindows.argtypes = [w.HWND, callback, w.LPARAM]+env = os.environ.copy()+env['TEMP'] = env['TMP'] = 'E:/项目/Veyra/tmp/5060-presets-subtitles-20260918'+process = None+++def send(h, msg, a=0, b=0):+ value = c.c_size_t()+ assert u.SendMessageTimeoutW(h, msg, a, b, 2, 1500, c.byref(value)), 'UI timeout'+ return value.value+++def find(cls, parent=None):+ found = []+ @callback+ def visit(h, unused):+ pid = w.DWORD(); u.GetWindowThreadProcessId(h, c.byref(pid))+ name = c.create_unicode_buffer(80); u.GetClassNameW(h, name, 80)+ if pid.value == process.pid and name.value == cls: found.append(h)+ return True+ if parent: u.EnumChildWindows(parent, visit, 0)+ else: u.EnumWindows(visit, 0)+ return found[0] if found else None+++def wait(predicate, seconds=8):+ until = time.monotonic() + seconds+ while time.monotonic() < until:+ value = predicate()+ if value: return value+ assert process.poll() is None, 'Application exited'+ time.sleep(.03)+ raise AssertionError('UI condition timeout')+++def rect(h):+ r = w.RECT(); assert u.GetWindowRect(h, c.byref(r))+ return [r.left, r.top, r.right, r.bottom]+++def launch(stage, extra):+ global process+ env['VEYRA_LOG_FILE'] = str(out / (stage + '.log'))+ process = subprocess.Popen([str(build/'veyra.exe'), str(media), '--smoke-seconds', '90', *extra],+ cwd=build, env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)+ main = wait(lambda: find('VeyraApp'))+ u.SetWindowPos(main, c.c_void_p(-1), 10, 10, 1180, 800, 0x40)+ u.SetForegroundWindow(main)+ return main+++def close(main):+ send(main, 0x10)+ assert process.wait(timeout=15) == 0+++result = {'bitmap': [], 'presetLayouts': []}+store = build/'runtime_local'/'color-looks.v1'+saved_store = store.read_bytes() if store.exists() else None+try:+ main = launch('bitmap-ui', ['--subtitle-primary', '0'])+ overlay = wait(lambda: find('VeyraSubtitleOverlay', main))+ wait(lambda: u.IsWindowVisible(overlay))+ send(main, 0x111, 102) # pause at first display+ time.sleep(.3)+ for mode in ['window', 'resize', 'fullscreen']:+ if mode == 'resize': u.SetWindowPos(main, None, 10, 10, 900, 640, 0x14)+ if mode == 'fullscreen': send(main, 0x111, 120)+ time.sleep(.4)+ bounds = rect(overlay)+ on = ImageGrab.grab(bbox=tuple(bounds), all_screens=True).convert('RGB')+ on.save(out/(mode+'-on.png'))+ send(main, 0x111, 225)+ wait(lambda: not u.IsWindowVisible(overlay))+ time.sleep(.15)+ off = ImageGrab.grab(bbox=tuple(bounds), all_screens=True).convert('RGB')+ off.save(out/(mode+'-off.png'))+ diff = ImageChops.difference(on, off)+ width, height = on.size+ fit = min(width/1280, height/720)+ ox, oy = (width-1280*fit)/2, (height-720*fit)/2+ regions = []+ for x, y in [(100, 600), (900, 100)]:+ # The opaque white half differs from both source colors. Red over+ # the source's red bar can legitimately produce no difference.+ box = (int(ox+(x+6)*fit), int(oy+(y+2)*fit), int(ox+(x+30)*fit), int(oy+(y+22)*fit))+ pixels = list(diff.crop(box).getdata())+ changed = sum(max(p)>20 for p in pixels)+ assert changed > len(pixels)*.6, (mode, box, changed, len(pixels))+ regions.append({'box': box, 'changedPixels': changed, 'totalPixels': len(pixels)})+ diff.save(out/(mode+'-diff.png'))+ result['bitmap'].append({'mode': mode, 'regions': regions})+ send(main, 0x111, 225)+ wait(lambda: u.IsWindowVisible(overlay))+ send(main, 0x111, 120) # restore window+ send(main, 0x111, 102) # resume and observe timed clear+ wait(lambda: not u.IsWindowVisible(overlay), 5)+ result['timedClear'] = True+ close(main)++ name = 'UI-验收命名-' + str(time.time_ns())+ for stage in ['save', 'reload']:+ main = launch('preset-'+stage, ['--colour-page'])+ body = wait(lambda: find('VeyraInspectorBody', main))+ control = lambda ident: u.GetDlgItem(body, ident)+ wait(lambda: u.IsWindowVisible(control(804)))+ if stage == 'save':+ for width, height in [(1180, 800), (900, 640)]:+ u.SetWindowPos(main, None, 10, 10, width, height, 0x14)+ time.sleep(.3)+ if not u.IsWindowVisible(body): send(main, 0x111, 229)+ for ident in range(805, 810):+ for unused in range(100):+ box, viewport = rect(control(ident)), rect(body)+ if viewport[1]<=box[1] and box[3]<=viewport[3]: break+ send(body, 0x115, 0 if box[1]<viewport[1] else 1)+ else: raise AssertionError(('Unreachable preset action', ident))+ point = w.POINT((box[0]+box[2])//2, (box[1]+box[3])//2)+ u.ScreenToClient(body, c.byref(point))+ hit = u.ChildWindowFromPointEx(body, point, 1)+ if hit != control(ident):+ ImageGrab.grab(bbox=tuple(rect(main)), all_screens=True).save(out/'preset-failure.png')+ raise AssertionError(('Occluded button', width, ident, box, viewport, point.x, point.y, hit, control(ident)))+ boxes = [rect(control(i)) for i in range(805, 810)]+ result['presetLayouts'].append({'width': width, 'boxes': boxes})+ ImageGrab.grab(bbox=tuple(rect(main)), all_screens=True).save(out/f'preset-layout-{width}.png')+ name_buffer = c.create_unicode_buffer(name)+ send(control(804), 0xc, 0, c.addressof(name_buffer))+ readback = c.create_unicode_buffer(256)+ send(control(804), 0xd, 256, c.addressof(readback))+ assert readback.value == name, ('Name edit', name, readback.value)+ try:+ send(control(805), 0xf5)+ except AssertionError:+ dialog = find('#32770')+ if dialog:+ labels = []+ @callback+ def collect(h, unused):+ buf = c.create_unicode_buffer(512)+ send(h, 0xd, 512, c.addressof(buf)); labels.append(buf.value)+ return True+ u.EnumChildWindows(dialog, collect, 0)+ print('Modal:', labels, flush=True)+ raise+ wait(lambda: store.exists() and name in store.read_text(encoding='utf-8'))+ else:+ count = send(control(803), 0x146)+ found = False+ for index in range(count):+ text = c.create_unicode_buffer(256)+ send(control(803), 0x148, index, c.addressof(text))+ found |= text.value == name+ assert found, 'Named preset missing after actual process restart'+ result['presetRestart'] = True+ close(main)+ result['passed'] = True+ (out/'result.json').write_text(json.dumps(result, indent=2), encoding='utf-8')+ print('PASS bitmap pixels, authored positions, resize, fullscreen, toggle, timed clear; preset hit targets, naming and process restart')+finally:+ if process and process.poll() is None: process.kill(); process.wait()+ if saved_store is None:+ store.unlink(missing_ok=True)+ else:+ store.write_bytes(saved_store)diff --git a/scripts/tests/make-bitmap-subtitle-fixture.py b/scripts/tests/make-bitmap-subtitle-fixture.pynew file mode 100644index 00000000..c84c51b2--- /dev/null+++ b/scripts/tests/make-bitmap-subtitle-fixture.py@@ -0,0 +1,44 @@+"""Deterministic PGS test data, decoded by the product's FFmpeg (no custom decoder).++Two authored rectangles, partial alpha, clear display sets and palette changes.+Output paths are explicit; invoke FFmpeg separately to mux with a test video.+"""+import pathlib+import struct+import sys+++def segment(seconds, kind, payload):+ return b"PG" + struct.pack(">IIBH", round(seconds * 90000), 0, kind, len(payload)) + payload+++def display(seconds, sequence, visible, palette=0):+ objects = [(0, 100, 600), (1, 900, 100)] if visible else []+ pcs = struct.pack(">HHBHBBBB", 1280, 720, 0x10, sequence, 0x80, 0, palette, len(objects))+ for object_id, x, y in objects:+ pcs += struct.pack(">HBBHH", object_id, 0, 0, x, y)+ data = segment(seconds, 0x16, pcs)+ if visible:+ data += segment(seconds, 0x17, struct.pack(">BBHHHH", 1, 0, 0, 0, 1280, 720))+ # YCrCb + alpha: white and half-transparent red, swapped on the second display.+ entries = [(235, 128, 128, 255), (81, 240, 90, 128)]+ if palette:+ entries.reverse()+ pds = bytes([palette, 0, 0, 16, 128, 128, 0])+ for index, color in enumerate(entries, 1):+ pds += bytes([index, *color])+ data += segment(seconds, 0x14, pds)+ for object_id, _, _ in objects:+ # Alternating colored halves with a transparent border.+ row = bytes([0, 0x84, 0, 0, 0x9C, 1, 0, 0x9C, 2, 0, 0x84, 0, 0, 0])+ pixels = row * 24+ ods = struct.pack(">HBB", object_id, 0, 0xC0)+ ods += (len(pixels) + 4).to_bytes(3, "big") + struct.pack(">HH", 64, 24) + pixels+ data += segment(seconds, 0x15, ods)+ return data + segment(seconds, 0x80, b"")+++target = pathlib.Path(sys.argv[1])+target.parent.mkdir(parents=True, exist_ok=True)+target.write_bytes(display(1, 0, True) + display(3, 1, False) + display(5, 2, True, 1) + display(7, 3, False))+print(target)diff --git a/src/engine/Subtitles.cpp b/src/engine/Subtitles.cppindex b6466592..590556b0 100644--- a/src/engine/Subtitles.cpp+++ b/src/engine/Subtitles.cpp@@ -14,6 +14,7 @@#include <condition_variable>#include <mutex>#include <thread>+#include <limits>extern "C" {#include <libavcodec/avcodec.h>@@ -391,6 +392,15 @@ std::wstring subtitleAt(const std::vector<SubtitleCue>& cues,double seconds){return {};}+std::vector<uint32_t> SubtitleBitmap::pixels()const{+ if(width<=0||height<=0||width>8192||height>8192)return {};+ const size_t count=size_t(width)*height;+ std::vector<uint32_t> result;result.reserve(count);+ for(const auto run:runs){const auto n=run>>8;if(!n||n>count-result.size())return {};result.insert(result.end(),n,palette[run&255]);}+ if(result.size()!=count)return {};+ return result;+}+std::vector<SubtitleTrack> loadEmbeddedSubtitleTracks(const std::wstring& path,std::stop_token stop,const std::function<void(const std::vector<SubtitleTrack>&)>& metadata){std::vector<SubtitleTrack> tracks;@@ -428,14 +438,16 @@ std::vector<SubtitleTrack> loadEmbeddedSubtitleTracks(const std::wstring& path,strack.styles.push_back(SubtitleStyle{});streamToTrack[streamIndex]=int(tracks.size());decoders.emplace_back();- if(!isTextSubtitleCodec(track.codec)){- track.note=L"图形/字幕格式不支持(本版本仅支持文本字幕)";+ const auto codec=stream->codecpar->codec_id;+ if(!isTextSubtitleCodec(track.codec)&&codec!=AV_CODEC_ID_HDMV_PGS_SUBTITLE&&codec!=AV_CODEC_ID_DVD_SUBTITLE&&codec!=AV_CODEC_ID_DVB_SUBTITLE){+ track.note=L"暂不支持此字幕格式";log::info("subtitle",std::format("embedded track {} codec={} listed as unsupported",streamIndex,codecName?codecName:""));tracks.push_back(std::move(track));continue;}const AVCodec* decoder=avcodec_find_decoder(stream->codecpar->codec_id);AVCodecContext* context=decoder?avcodec_alloc_context3(decoder):nullptr;+ if(context){context->pkt_timebase=stream->time_base;}if(!decoder||!context||avcodec_parameters_to_context(context,stream->codecpar)<0||avcodec_open2(context,decoder,nullptr)<0){track.note=L"字幕解码器初始化失败";if(context)avcodec_free_context(&context);@@ -451,6 +463,10 @@ std::vector<SubtitleTrack> loadEmbeddedSubtitleTracks(const std::wstring& path,sstruct PacketCleanup {AVPacket*& packet;~PacketCleanup(){av_packet_free(&packet);}} packetCleanup{packet};constexpr size_t maxCacheBytes=64u*1024u*1024u;size_t cacheBytes=0,totalCues=0;uint64_t packets=0;+ int videoWidth=1920,videoHeight=1080;+ for(unsigned i=0;i<input->nb_streams;++i)if(input->streams[i]->codecpar->codec_type==AVMEDIA_TYPE_VIDEO){+ videoWidth=std::max(1,input->streams[i]->codecpar->width);videoHeight=std::max(1,input->streams[i]->codecpar->height);break;+ }auto nextPublish=std::chrono::steady_clock::now()+std::chrono::milliseconds(250);while(packet&&!stop.stop_requested()&&av_read_frame(input,packet)>=0){++packets;@@ -461,7 +477,51 @@ std::vector<SubtitleTrack> loadEmbeddedSubtitleTracks(const std::wstring& path,sAVSubtitle subtitle{};int got=0;if(avcodec_decode_subtitle2(context,&subtitle,&got,packet)<0||!got){avsubtitle_free(&subtitle);av_packet_unref(packet);continue;}- const double packetSeconds=packet->pts==AV_NOPTS_VALUE?0:double(packet->pts)*timeBase;+ const double packetSeconds=(subtitle.pts!=AV_NOPTS_VALUE?double(subtitle.pts)/AV_TIME_BASE:+ packet->pts==AV_NOPTS_VALUE?0:double(packet->pts)*timeBase);+ const bool bitmapCodec=context->codec_id==AV_CODEC_ID_HDMV_PGS_SUBTITLE||context->codec_id==AV_CODEC_ID_DVD_SUBTITLE||context->codec_id==AV_CODEC_ID_DVB_SUBTITLE;+ if(bitmapCodec){+ const double begin=packetSeconds+double(subtitle.start_display_time)/1000.0;+ // A new display set (including an empty clear set) replaces the old one.+ if(!track.cues.empty()&&begin>=track.cues.back().begin){+ if(begin==track.cues.back().begin)track.cues.pop_back();+ else track.cues.back().end=std::min(track.cues.back().end,begin);+ }+ auto frame=std::make_shared<SubtitleBitmapFrame>();+ frame->width=context->width>0?context->width:videoWidth;+ frame->height=context->height>0?context->height:videoHeight;+ size_t bytes=sizeof(SubtitleCue)+sizeof(SubtitleBitmapFrame);+ bool valid=bytes<=maxCacheBytes-cacheBytes&&subtitle.num_rects<=256;+ for(unsigned r=0;r<subtitle.num_rects&&valid;++r){+ const auto* rect=subtitle.rects[r];+ if(!rect||rect->type!=SUBTITLE_BITMAP)continue;+ if(rect->w<=0||rect->h<=0||rect->w>8192||rect->h>8192||!rect->data[0]||!rect->data[1]||rect->linesize[0]<rect->w||rect->nb_colors<1||rect->nb_colors>256){valid=false;break;}+ if(sizeof(SubtitleBitmap)>maxCacheBytes-cacheBytes-bytes){valid=false;break;}+ const size_t runBudget=(maxCacheBytes-cacheBytes-bytes-sizeof(SubtitleBitmap))/sizeof(uint32_t);+ SubtitleBitmap image;image.x=rect->x;image.y=rect->y;image.width=rect->w;image.height=rect->h;+ for(int p=0;p<rect->nb_colors;++p){+ uint32_t c=0;std::memcpy(&c,rect->data[1]+p*4,4);const uint32_t a=c>>24;+ image.palette[p]=(a<<24)|((((c>>16)&255)*a/255)<<16)|((((c>>8)&255)*a/255)<<8)|((c&255)*a/255);+ }+ for(int y=0;y<rect->h&&valid;++y)for(int x=0;x<rect->w;++x){+ const uint8_t pixel=rect->data[0][size_t(y)*rect->linesize[0]+x];+ if(pixel>=rect->nb_colors){valid=false;break;}+ if(!image.runs.empty()&&(image.runs.back()&255)==pixel&&(image.runs.back()>>8)<0xFFFFFF)image.runs.back()+=256;+ else {if(image.runs.size()>=runBudget){valid=false;break;}image.runs.push_back(256u|pixel);}+ }+ if(!valid)break;+ bytes+=sizeof(SubtitleBitmap)+image.runs.size()*sizeof(uint32_t);+ frame->images.push_back(std::move(image));+ }+ if(valid&&!frame->images.empty()){+ SubtitleCue cue;cue.begin=begin;+ cue.end=subtitle.end_display_time>subtitle.start_display_time&&subtitle.end_display_time!=UINT32_MAX?+ packetSeconds+double(subtitle.end_display_time)/1000.0:std::numeric_limits<double>::infinity();+ cue.bitmap=std::move(frame);+ if(totalCues<kMaxCues&&bytes<=maxCacheBytes-cacheBytes){cacheBytes+=bytes;++totalCues;track.cues.push_back(std::move(cue));}+ else track.note=L"字幕缓存已达上限,后续字幕未加载";+ }else if(!valid){track.note=L"图形字幕数据无效或超出缓存上限";log::warn("subtitle","bitmap display rejected: invalid rectangle or cache budget");}+ }for(unsigned rect=0;rect<subtitle.num_rects;++rect){const auto* entry=subtitle.rects[rect];if(!entry)continue;diff --git a/src/source/CaptureCardSource.cpp b/src/source/CaptureCardSource.cppindex 6b2aaba3..e05ee605 100644--- a/src/source/CaptureCardSource.cpp+++ b/src/source/CaptureCardSource.cpp@@ -216,6 +216,7 @@ struct CaptureCardSource::Impl:ISampleGrabberCB {double pendingTime=0,lastPts=0,readAgeMs=0;bool pendingDiscontinuity=false,forceDiscontinuity=false;int64_t nominalDuration100ns=0;pipeline::Rational pendingDuration=pipeline::Rational::unknown();uint64_t received=0,dropped=0,lastDrop=0,sequence=0;+ uint64_t discontinuitySamples=0;Clock::time_point pendingArrival{},readArrival{},firstArrival{},latestArrival{};ComPtr<IGraphBuilder> graph;ComPtr<ICaptureGraphBuilder2> builder;ComPtr<IBaseFilter> device,grabFilter,nullFilter,audioFilter;ComPtr<IAMStreamConfig> config;ComPtr<ISampleGrabber> grab;ComPtr<IMediaControl> control;ComPtr<IMediaEvent> events;float lastAudioGain=-1;bool audioGainSupported=false;@@ -354,6 +355,14 @@ struct CaptureCardSource::Impl:ISampleGrabberCB {// empty between reads; only the native path requires it here.if(!valid||(!compressedPath&&!pendingFrame)){callbackError=true;}else {+ const double previous=compressedPath?lastCallbackTime:pendingTime;+ const bool driverBreak=sample->IsDiscontinuity()==S_OK;+ const bool clockBreak=received&&(time<=previous||time-previous>(info.averageFps>0?2.5/info.averageFps:.1));+ if(driverBreak||clockBreak){+ ++discontinuitySamples;+ if(discontinuitySamples<=4||discontinuitySamples%120==0)+ log::warn("capture-discontinuity",std::format("source={} count={} driverFlag={} clockBreak={} previousPtsMs={:.4f} ptsMs={:.4f} deltaMs={:.4f} arrivalDeltaMs={:.4f} sampleStart={} sampleEnd={} completeTime={} nominalFps={:.4f}",received+1,discontinuitySamples,driverBreak,clockBreak,previous*1000,time*1000,(time-previous)*1000,received?std::chrono::duration<double,std::milli>(arrival-latestArrival).count():0.0,sampleStart,sampleEnd,sampleTime,info.averageFps));+ }// Copy directly into our bounded mailbox; read() swaps frames// under this lock, so the frame consumed by the GPU is untouched.// Compressed payloads are decoded by our own backend instead of@@ -366,7 +375,7 @@ struct CaptureCardSource::Impl:ISampleGrabberCB {if(compressedQueue.size()>=compressedQueueLimit){compressedQueue.pop_front();++compressedDropped;++dropped;}CompressedSample entry;entry.payload.assign(payload,payload+bytes);entry.time=time;entry.arrival=arrival;entry.start=sampleStart;entry.end=sampleEnd;entry.completeTime=sampleTime;- entry.bad=captureDiscontinuity(!compressedQueue.empty()||pending,pendingDiscontinuity,sample->IsDiscontinuity()==S_OK,received>0,lastCallbackTime,time,info.averageFps);+ entry.bad=captureDiscontinuity(!compressedQueue.empty()||pending,pendingDiscontinuity,driverBreak,received>0,lastCallbackTime,time,info.averageFps);pendingDiscontinuity=entry.bad;lastCallbackTime=time;compressedQueue.push_back(std::move(entry));enqueued=true;}else{@@ -375,7 +384,7 @@ struct CaptureCardSource::Impl:ISampleGrabberCB {// Inspect consecutive callbacks, not consecutive mailbox reads.// Preserve a driver/clock break when its sample is overwritten.pendingDiscontinuity=captureDiscontinuity(pending,pendingDiscontinuity,- sample->IsDiscontinuity()==S_OK,received>0,pendingTime,time,info.averageFps);+ driverBreak,received>0,pendingTime,time,info.averageFps);pending=true;pendingTime=time;pendingArrival=arrival;pendingDuration=captureDuration(sampleStart,sampleEnd,sampleTime,nominalDuration100ns);}diff --git a/tests/integration/BitmapSubtitleTests.cpp b/tests/integration/BitmapSubtitleTests.cppnew file mode 100644index 00000000..f9481858--- /dev/null+++ b/tests/integration/BitmapSubtitleTests.cpp@@ -0,0 +1,48 @@+#include "veyra/engine/Subtitles.h"+#include <cmath>+#include <iostream>++int wmain(int argc,wchar_t** argv){+ using namespace veyra::engine;+ if(argc!=2)return 2;+ int failed=0;+ auto check=[&](bool pass,const char* name){std::cout<<(pass?"PASS ":"FAIL ")<<name<<'\n';failed+=!pass;};+ const auto tracks=loadEmbeddedSubtitleTracks(argv[1]);+ check(tracks.size()==1,"bitmap embedded track discovered");+ if(tracks.size()!=1)return 1;+ const auto& track=tracks.front();+ check(track.cues.size()==2,"clear display sets close cues without becoming visible cues");+ if(track.cues.size()!=2)return 1;+ const bool dvd=track.codec==L"dvd_subtitle";+ const double tolerance=dvd?.012:.001; // DVD dates use 1024/90000-second ticks.+ for(const auto& cue:track.cues)std::cout<<"cue="<<cue.begin<<","<<cue.end<<'\n';+ check(std::abs(track.cues[0].begin-1)<tolerance&&std::abs(track.cues[0].end-3)<tolerance,"first cue has codec-accurate display timing");+ check(std::abs(track.cues[1].begin-5)<tolerance&&std::abs(track.cues[1].end-7)<tolerance,"second cue has codec-accurate display timing");+ for(double t:{0.,3.,4.,7.,8.})check(cuesAt(track,t).empty(),"clear gap remains empty including exact boundary");+ for(double t:{6.,2.,5.,1.})check(cuesAt(track,t).size()==1,"random access and backward seek retain correct bitmap");+ const auto frame=track.cues[0].bitmap;+ if(dvd){+ check(frame&&frame->images.size()==1,"DVD encoder merges authored rectangles");+ if(!frame||frame->images.size()!=1)return 1;+ const auto& image=frame->images[0];const auto pixels=image.pixels();+ check(pixels.size()==size_t(image.width)*image.height,"merged DVD bitmap expands exactly");+ auto alpha=[&](int x,int y){x-=image.x;y-=image.y;return x>=0&&y>=0&&x<image.width&&y<image.height&&!pixels.empty()?pixels[size_t(y)*image.width+x]>>24:0u;};+ check(alpha(110,610)>0&&alpha(910,110)>0&&alpha(500,350)==0,"DVD retains both authored areas and transparent gap");+ return failed?1:0;+ }+ check(frame&&frame->images.size()==2,"multiple authored rectangles retained in one display set");+ if(!frame||frame->images.size()!=2)return 1;+ check(frame->width==1280&&frame->height==720,"authored canvas retained");+ bool lower=false,upper=false;+ for(const auto& image:frame->images){lower|=image.x==100&&image.y==600;upper|=image.x==900&&image.y==100;}+ check(lower&&upper,"authored positions retained regardless of codec rectangle order");+ const auto pixels=frame->images[0].pixels();+ check(pixels.size()==64*24,"indexed runs expand exactly");+ if(pixels.size()!=64*24)return 1;+ check(pixels[0]==0&&(pixels[5]>>24)==255&&(pixels[35]>>24)==128,"transparent opaque and partial alpha preserved");+ check(((pixels[35]>>16)&255)<=128&&((pixels[35]>>8)&255)<=128&&(pixels[35]&255)<=128,"alpha is premultiplied for layered window");+ check(track.cues[1].bitmap->images[0].pixels()[5]!=pixels[5],"palette change preserved in immutable snapshots");+ auto corrupt=frame->images[0];corrupt.runs.push_back(256);+ check(corrupt.pixels().empty(),"malformed cached runs fail without overrun");+ return failed?1:0;+}diff --git a/tests/unit/UiContractTests.cpp b/tests/unit/UiContractTests.cppindex 1d29c7fa..0bee2687 100644--- a/tests/unit/UiContractTests.cpp+++ b/tests/unit/UiContractTests.cpp@@ -6,6 +6,7 @@#include "../../apps/veyra/ui/CapturePreferenceStore.h"#include "../../apps/veyra/ui/SourceTitle.h"#include "veyra/engine/EngineController.h"+#include "../../apps/veyra/ui/LiveStatusHistory.h"#include "veyra/sink/AudioGain.h"#include "veyra/engine/PreviewView.h"#include <iostream>@@ -14,6 +15,22 @@void require(bool value,const char* why){if(!value)throw std::runtime_error(why);}int wmain(int argc,wchar_t** argv){try{using namespace veyra;+ {+ ui::live_status::DashboardHistory history;engine::PlayerSnapshot s;+ s.running=s.capture=true;s.transport=engine::TransportState::Playing;s.sessionId=1;s.applied.revision=1;+ s.captureReceived=120;s.captureFps=40;s.nominalSourceFps=60;s.applied.multiplier=4;+ s.metrics.flow.rateWindowReady=true;s.metrics.flow.presentSubmitFps=160;+ for(int i=0;i<9;++i)history.sample(s);+ require(!history.overloaded&&history.inputLimited,"40fps source delivering160fps at4X is input limited, not FG limited");+ s.captureFps=60;s.metrics.flow.presentSubmitFps=120;+ for(int i=0;i<9;++i)history.sample(s);+ require(history.overloaded&&!history.inputLimited,"actual output deficit remains visible");+ s.applied.multiplier=1;s.fgBudgetLimited=true;+ require(std::wstring(history.rateStatus(s))!=L"补帧调度降档","disabled FG cannot report FG throttling");+ for(int i=1;i<8;++i){s.metrics.flow.reset.epoch=i*10;history.sample(s);}+ require(history.resetSamples>=3,"continuous reset storm is identified separately");+ s.applied.revision=2;history.sample(s);require(!history.overloaded&&!history.inputLimited&&!history.resetSamples,"revision invalidates stale warnings");+ }{engine::PresentationCadence c;require(c.due(100,10)==100,"no startup pacing reserve");c.submitted(108);require(c.due(110,10)==117,"front edge spaces late outputs with bounded catch-up");c.submitted(999);require(c.due(120,10)==1008,"stale subframe cannot burst after stall");c.reset();require(c.due(120,10)==120,"reset revokes optional deadline");}{engine::PreviewView v;v.wheel(3,800,300,1000,600,1920,1080);require(std::abs(v.zoom-1.728f)<.0001f,"wheel scale");const float anchored=(800-500)/(1920.0f*(1000.0f/1920)*v.zoom)+v.centerX;require(std::abs(anchored-.8f)<.0001f,"pointer anchor fixed");