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++
Export page: ordered editable queue, MKV with all audio/subtitle tracks, cancel-and-retry fix, completion sound
Veyra Goal Agente892c6a19984
diff --git a/AGENTS.md b/AGENTS.mdindex ff2ec0ae..3d5e3379 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -1,5 +1,7 @@# Veyra 项目 Agent 执行规则+> **2026-10-02 导出优化目标授权(用户:“开启目标模式搞定他”)**:按 `docs/EXPORT_PAGE_OPTIMIZATION_PLAN_2026-10-02.md` 在 `E:/项目/Veyra/worktrees/export-page-20261002` / `codex/export-page-20261002` 实现导出页布局、可编辑顺序队列、MKV/多音轨/内嵌字幕、取消重试及完成提示音,并做真实验收。本条仅解除该方案列出的导出后端、QML/bridge、必要 CMake 与定向测试接点的历史冻结;其他链路不改。每轮先执行本分支 `python -B scripts/acceptance/export-page-control.py`,不可变基线在 `E:/项目/Veyra/archives/export-page-20261002-start/scope-baseline.json`,不得修改旧桌面 guard/baseline。Claude 的其他工作区、主分支、已有候选与用户配置保持原样;专用 E 盘构建/测试/TEMP,不派子 Agent,不 commit/tag/merge/push/Release。单测试≤300秒,构建≤900秒;已有 runtime/patched FFmpeg 身份和源码隔离约束保持。+> **2026-10-01 2.0.0 合并 main 授权(用户:“基本上2.0.0已经没啥问题了,剩下一些小bug和功能我后面再和你对,现在分支有点多……先合并一手,存档一下,更新更新文档,对齐目前进度”)**:整理 2.0.0 各分支并合并到**本地** `main`;先存档到 `E:/项目/Veyra/archives/merge-2.0.0-20261001/`(全引用 git bundle、合并前两处未提交状态、SHA256),打 `checkpoint/pre-merge-2.0.0-main-20261001`、`checkpoint/2.0.0-branch-tip-20261001`、`checkpoint/merged-2.0.0-20261001` 标签,合并后更新文档。授权范围:commit、打标签、本地 `--no-ff` 合并、删除已并入 `main` 且指向同一提交的重复分支名。**不含** push、GitHub Release、Runtime Pack 上传、删除旧 Win32 界面、删除 worktree 或用户文件、改动桌面原目录;这些仍需另行授权。此后 2.0.0 的新工作从 `main` 另开分支;本文件此前条目中的 `codex/*-2026092x/30` 阶段分支名均已并入 `main`,见 `docs/BRANCH_MAP_2026-10-01.md`。> **2026-09-30 真人反馈修复授权**:先存档,再将 RTX40 NR 改为 SF-v2、RTX50 保留 Lecram,NR 节点提供双版本选择,淘汰新候选中的旧40运行库;随后按用户指定 `FIX_PLAN_1.4.4_FIELD_ISSUES_2026-09-30.md` 排查修复。仅在 E 盘 `p0-p1-r53-20260927`、新分支 `codex/field-issues-20260930`;保留当前 FSR/XeSS 和全部既有改动。必要的 NR 选择/配置迁移、GPU 故障、呈现、采集协商、HDR/比例/运动输入、分辨率/导出反馈修复接点获本轮授权,覆盖这些接点的历史冻结;无关改造仍冻结。范围、存档和验收见 `docs/FIELD_ISSUES_EXECUTION_2026-09-30.md`。原桌面 checkout、main、原 beta/历史发布/下载原件保留;不 commit/tag/merge/push/Release,不派子 Agent。新候选可原样使用已批准 Lecram/SF-v2,不 patch、不入源码 Git。diff --git a/CMakeLists.txt b/CMakeLists.txtindex ae97972b..e6107e0a 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -698,6 +698,14 @@ if(VEYRA_FFMPEG_ROOT AND EXISTS "${VEYRA_FFMPEG_ROOT}/include/libavformat/avformadd_executable(veyra_repair_fg_tests tests/integration/RepairFgTests.cpp)add_executable(veyra_export_frame_pool_tests tests/integration/ExportFramePoolTests.cpp)add_executable(veyra_export_worker_failure_tests tests/integration/ExportWorkerFailureTests.cpp)+ add_executable(veyra_export_workflow_tests tests/integration/ExportWorkflowTests.cpp)+ target_compile_features(veyra_export_workflow_tests PRIVATE cxx_std_20)+ target_compile_options(veyra_export_workflow_tests PRIVATE /utf-8)+ target_link_libraries(veyra_export_workflow_tests PRIVATE veyra_engine)+ add_executable(veyra_export_queue_tests tests/unit/ExportQueueTests.cpp)+ target_compile_features(veyra_export_queue_tests PRIVATE cxx_std_20)+ target_compile_options(veyra_export_queue_tests PRIVATE /utf-8)+ target_link_libraries(veyra_export_queue_tests PRIVATE veyra_engine)target_compile_features(veyra_export_worker_failure_tests PRIVATE cxx_std_20)target_link_libraries(veyra_export_worker_failure_tests PRIVATE veyra_engine)add_executable(veyra_fg_lifecycle_tests tests/integration/FgLifecycleTests.cpp)@@ -758,7 +766,7 @@ endif()# separate small library rather than into veyra_engine: the product build must# never depend on Qt being installed.if(VEYRA_BUILD_QML_UI AND Qt6_FOUND)- add_library(veyra_qml_bridge STATIC src/ui/QmlPlayerBridge.cpp src/ui/ThumbnailProvider.cpp+ add_library(veyra_qml_bridge STATIC src/ui/QmlExportQueueModel.cpp include/veyra/ui/QmlExportQueueModel.h src/ui/QmlPlayerBridge.cpp src/ui/ThumbnailProvider.cppinclude/veyra/ui/QmlPlayerBridge.h include/veyra/ui/ThumbnailProvider.h# P4-c: the existing subtitle renderer, reused as-is (no second renderer).apps/veyra/ui/SubtitleOverlay.cpp)@@ -875,7 +883,7 @@ add_executable(veyra_sr_reconstruction_tests tests/integration/SrReconstructionTtarget_link_libraries(veyra_repair_fg_tests PRIVATE veyra_pipeline veyra_sinks veyra_nvof)# Headless quality-core runner (Playbook R3.3): the phase5 gate's quality- add_library(veyra_engine STATIC src/engine/EngineController.cpp src/engine/EngineControllerImage.cpp src/engine/PosterFrame.cpp src/engine/EffectChain.cpp src/engine/PresetLibrary.cpp src/ui/PlayerUiFacade.cpp src/engine/TiledImageProcessor.cpp src/engine/PresetStore.cpp src/engine/VideoPresenter.cpp src/engine/VideoExportJob.cpp src/engine/ExportJobManager.cpp src/engine/Subtitles.cpp src/engine/FgCompatibilityProbe.cpp)+ add_library(veyra_engine STATIC src/engine/EngineController.cpp src/engine/EngineControllerImage.cpp src/engine/PosterFrame.cpp src/engine/EffectChain.cpp src/engine/PresetLibrary.cpp src/ui/PlayerUiFacade.cpp src/engine/TiledImageProcessor.cpp src/engine/PresetStore.cpp src/engine/VideoPresenter.cpp src/engine/VideoExportJob.cpp src/engine/ExportStreams.cpp src/engine/ExportQueue.cpp src/engine/ExportJobManager.cpp src/engine/Subtitles.cpp src/engine/FgCompatibilityProbe.cpp)target_sources(veyra_pipeline PRIVATE src/guidance/AmdOpticalFlow.cppsrc/guidance/GpuDisOpticalFlow.cpp third_party/gpu-dis/src/gpu/native_strict_dis_provider.cpp)target_include_directories(veyra_pipeline PRIVATE third_party/gpu-dis/src/gpu)diff --git a/docs/EXPORT_PAGE_EXECUTION_2026-10-02.md b/docs/EXPORT_PAGE_EXECUTION_2026-10-02.mdnew file mode 100644index 00000000..2797a0c2--- /dev/null+++ b/docs/EXPORT_PAGE_EXECUTION_2026-10-02.md@@ -0,0 +1,88 @@+# Veyra 导出优化执行与验收记录++2026-10-02 用户授权目标模式完成导出优化。分支 `codex/export-page-20261002`,工作区 `E:/项目/Veyra/worktrees/export-page-20261002`,起点 `09392c4d66b267cc75269b068aaffe3189830d37`。产品改动和本机定向验收已完成,没有提交、合并、推送或发布。++## 实现++- 左侧添加支持多选及拖入,添加仅入队。支持点击预览、单项移除、清空、拖动排序。点击开始后串行导出当前批次;后加入的文件留到下一批。等待项可调整顺序或移除,当前执行项不能移除。各文件独立保留剪辑/轨道选择;开始时冻结本批设置。+- 右侧设置可滚动,底部操作固定可达,分辨率改为有边界的下拉框。小窗口切换文件/预览/设置页签;Main 与 ExportPage 共用布局计算,原生视频随页签隐藏。局部深色控件,不改变公共控件。+- MP4/MKV 与 H.264/HEVC 分开选择。默认全部音轨和内嵌字幕,也可逐文件选择或关闭。兼容轨道复制压缩包,保留声道、语言、标题和 default/forced。文字字幕必要时转换并标明样式损失;MKV 保留 ASS 字体附件。“全部”不限轨数;只有手动选择上限 64 条。+- 取消中/收尾状态持续轮询,回收 worker 进程后才发布终态。每次原子预留专属临时文件,取消只清理自己的文件。旧 partial 不阻塞重试;正式文件不覆盖。清理失败保留准确路径。已经安全保存的结果不因迟到的取消变成失败。+- 视频整批全部成功只提示一次;取消、失败、混合结果不播放成功音。图片批次采用同一规则。默认启用 Windows MessageBeep,可关闭并持久保存;实际可闻性受系统音量和声音方案控制。++新增 ExportQueue、QmlExportQueueModel、ExportStreams;复用现有单 worker、GPU 增强链和 D3D12 NVENC,没有另造播放/增强流水线、视频像素回读或修改媒体运行库。++## 隔离与产物++不可变基线 `E:/项目/Veyra/archives/export-page-20261002-start/scope-baseline.json`,SHA256 `d135f9ad55aacddc3ca5cf6f0771991b863306ebb5931d6e00c0a5aac9d4daae`,1109 文件。每轮 `python -B scripts/acceptance/export-page-control.py` PASS。未写其他工作区、旧 guard/baseline,未切换其他 checkout、stash/reset 或终止其他任务进程。其他 Agent 自行产生的变化不算本任务改动。++| 用途 | 绝对路径 |+|---|---|+| 最终可运行版本 | `E:/项目/Veyra/test-packages/export-page-20261002/veyra_qml_ui.exe` |+| 构建 | `E:/项目/Veyra/build/export-page-20261002` |+| 媒体、输出、截图、隔离配置 | `E:/项目/Veyra/tests/export-page-20261002` |+| 构建/测试日志 | `E:/项目/Veyra/logs/export-page-20261002` |+| 子进程 TEMP/TMP | `E:/项目/Veyra/tmp/export-page-20261002` |+| stage 工具临时目录 | `E:/项目/Veyra/tmp/ui-migration-stage/{baseline-app,candidate-ui-001,export-page-20261002}` |+| 增量源码归档 | `E:/项目/Veyra/archives/export-page-20261002-final` |++MSVC 2022、Qt 6.8.3、项目既有 patched FFmpeg(PS5 slice 补丁不变);系统 FFmpeg 8.1.1 仅生成/检查媒体。SDK/runtime/媒体不进入源码 Git。最终包 AMD/Intel 目录由 staging 链接转为逐文件哈希一致的独立副本,不依赖中间 staging,见 `final-runtime-copy.json`。保留既有 PreviewView 整数转 float 编译警告,不宣称零警告。++最终包可执行文件 SHA256 `4fe74b404f7d577ff212ca20cdf0f8fb0b793904c8c9598325ee3650a3be0310`,与构建相同;52 份 QML 源文件逐一一致,Main 中测试 Loader 已恢复移除。见 `final-audit.json`。中间 staging 删除命令被自动审批以 `blocked by policy` 拒绝,没有执行删除;`baseline-app`、`candidate-ui-001`、`engine-app` 及其日志全部保留,见 `cleanup-deferred.json`。没有通过其他工具绕过拒绝。++构建:`python -B scripts/acceptance/export-page-build.py <唯一日志名> <目标...>`,目标为 veyra_qml_ui、veyra_export_workflow_tests、veyra_export_queue_tests、veyra_export_worker_failure_tests、veyra_qml_quick_tests、veyra_qml_data_tests、veyra_qml_easing_tests。最终相关日志 `build-final-review-001.log`、`build-boundary-fix-001.log`、`build-boundary-test-001.log`,exit 0。++## 验收证据++日志名相对于上述 logs 目录。驱动 `python -B scripts/acceptance/export-page-tests.py <模式> <唯一标识> [素材]`;单次测试子进程上限 290 秒。++| 场景 | 本机结果及日志 |+|---|---|+| 准备/暂停/编码取消,同路径重试,worker 终态比退出早 1200ms | `lifecycle-final-001.log` PASS;foreign partial 保持 24 字节,最终 20 帧完整解码 |+| 保存前取消、清理遇占用、残留不阻塞重试、保存后取消 | `lifecycle-boundary-003.log` PASS;错误 32 和临时路径保留,安全落盘结果保持成功 |+| 20 文件仅添加、稳定 ID、拖排、独立 trim/选轨、冻结批次、清空 | `queue-unit-003.log` PASS |+| 真实 C/A/B 顺序,晚加 D 留下一批,混合失败不报全成功 | `queue-001.log` PASS;4 份 probe 各 30 帧、2 音轨、2 字幕 |+| 实际页面/bridge/model/worker,预览切换不打断导出,逐文件 trim 恢复 | `production-ui-final-001.log` PASS;截图及 profile 在 tests 下同名目录 |+| 提示音、静音、取消、失败、图片成功/冲突/取消 | 同上:视频整批成功一次声音请求、静音成功零次;图片整批成功一次;其余零次;关闭偏好保存 |+| 720×260、1280×720、1366×768、1920×1080,鼠标拖排/菜单边界 | `qml-1-full-001-results.log` 29/29,含本页 8 项;最终 200% `qml-2-final-001-results.log` 8/8 |+| 100/125/150/200% DPI | `qml-1-002`、`qml-1.25-002`、`qml-1.5-002`、`qml-2-002` 的 results 各 8/8;截图复核 |+| MP4/MKV × H.264/HEVC,双音轨、多字幕 | `mp4-001`、`mkv-001`、`mp4-hevc-001`、`mkv-hevc-001` 导出/probe/decode 通过 |+| mov_text→ASS、SRT→mov_text | `mkv-convert-001`、`mp4-convert-001` PASS |+| 0.7–1.7s 剪辑,跨入点文字字幕与出点截断 | `mkv-trim-001`、`mp4-trim-001`:10 帧;字幕 0–0.600s、0.800–1.000s,文字保留 |+| AAC 起始样本及压缩包完整性 | `mkv-002`、`mp4-002`、`track-content-001.json`:284 包内容相同;输入/输出各 144384 解码样本 |+| ASS 和字体附件 | `mkv-font-001`:ASS 包 SHA256 相同;TTF 1045720 字节,SHA256 b3658eadae55e682b5f69eb64c439c1ecc8f196c0bb8d4756d145d13bc86476a 相同 |+| 5.1 FLAC+多 AAC,无音轨,30s 稀疏字幕 | `mkv-six-001`、`mp4-silent-001`、`mkv-sparse-001` probe/视频音频解码通过 |+| 65 条音轨全部保留 | `mkv-sixty-five-001`:65 条,codec/声道/语言匹配,视频和全部音频解码通过 |+| 单独选轨、全部不保留 | `mkv-selected-001`、`mp4-none-001` PASS;选定字幕包内容一致 |+| PGS 整片复制 | `mkv-pgs-004-subtitle-packets.json`:输入/输出各 2 包 SHA256 相同,240 帧视频解码通过 |+| PGS→MP4、PGS 剪辑、不支持压缩 PGS | `mp4-pgs-reject-001`、`mkv-pgs-trim-reject-001`、`mkv-pgs-reject-005` 明确失败,无假成功正式文件 |+| 颜色导出链、数据隔离、QML 曲线 | `color-chain-003.log` 11/11(直接导出/worker 解码像素相同);`qml-data-003.log` PASS;`qml-easing-003.log` failures=0 |++真实视频导出使用 RTX 5070、NVENC D3D12。NR/SR/FG 算法未修改,没有由无增强/颜色链测试推断全部增强、AMD/Intel 实机或 HDR 通过。未人工听音。Qt contentItem 截图不包含独立 HWND 视频像素;真实预览和区域(636×532 at 282,56)有生产日志,不把截图黑色区域当成画面验证。整体 QML 套件保留旧 ProPage 测试的 veyra stub 警告,本页独立/真实测试没有对应 QML 错误。++## 失败记录和修复++1. MKV AAC 原始负时间 priming 包被丢弃,同时保留 CodecDelay,头部被重复扣除。完整导出保留 priming,剪辑清除原始 initial_padding;随后 payload/解码样本一致。+2. 官方 PGS 小样本使用了本机 patched 库不支持的轨道压缩。解复用只打印 Unsupported encoding type,自动 pgs_frame_merge 丢包但返回成功。早期 mkv-pgs-001/002/003 仅轨道头通过,**字幕内容失败,不算验收证据**。增加 PGS 包结构检查明确拒绝;以系统 FFmpeg 无损重封装为普通 PGS 后,产品两包内容相同。没有替换媒体库。+3. 故障注入发现通用 Cancelled 文案覆盖了临时文件删除失败路径;去掉覆盖后 lifecycle-boundary-003 通过。+4. 首次 QML 断言错误要求可滚动内容全部装进 viewport,且误以为截图 save 返回布尔值。改为边界/可达性与 PNG 检查。Windows 原生样式拒绝自定义选择器,本页使用 Basic 与深色滚动条/勾选框。+5. 边界测试起初错误等待进程回收前 100%(现有上限 99.9%),改以正式文件存在且进程仍活着观测。颜色链初测缺数据目录确认变量,补 VEYRA_TEST_COLOR_CHAIN_DATA_ROOT=本任务 engine-app/runtime_local 后通过。失败日志保留,没有覆盖。++PGS 来源 [FFmpeg samples](https://samples.ffmpeg.org/sub/PGS/supsample.mkv),23644 字节,SHA256 e6c8f93f57d0371603704d7e7b16933e6c4c5df669da42b42a2a84de881e0f27;本机 Arial 字体和样本只用于本地回归,不进入交付包。++## 明确限制++- **PGS/VobSub 等图片字幕只支持整片保留,带剪辑时明确拒绝该轨道组合。** 可以整片导出或排除此字幕轨道,没有伪装精确裁剪支持。+- 旧 MKV 中媒体库不支持的轨道压缩需要先无损重封装或排除该轨;不能静默丢字幕。字体附件只保留到输出,不安装。+- 音轨直接复制以包为边界,不承诺任意采样点精确剪辑;文字字幕显式裁剪入/出点。+- 节点链离线导出沿用现有不支持提示,本次不扩展其执行能力。+- 这是独立本地测试版本,源码留在本分支工作树待审查整合,没有新 Release。++## 2026-10-02 Claude 验收与修正++用户要求复核 Codex 本轮导出改动并合并 main。复核结论:取消回收、专属临时文件、队列冻结、MKV/多轨/字幕路径设计正确,原有验收全部重跑通过。发现并修正一处默认行为问题:++- **“保留全部”遇到当前封装装不下的轨道时整项失败。** 队列默认音轨/字幕均为“全部”、封装默认 MP4;常见 MKV 片源带 PGS 图片字幕(或剪辑时带任何图片字幕)会在预检阶段直接失败,比旧版(只带一条音轨、不带字幕)更容易导不出来。现改为:“全部”只表示“当前封装能装下的全部”,装不下的轨道跳过,在队列项说明和完成消息中列出(“部分轨道当前封装装不下,未保留”),音轨全被跳过时额外提示“导出的视频将没有声音”;用户手动选中的轨道装不下仍明确报错。从“全部”切换到手动选择时不再把被跳过的轨道带进手动选择。+- 页面轨道说明同步更新。++重跑(日志在 `E:/项目/Veyra/logs/export-page-20261002/*-claude1*`):mp4、mkv、mkv-trim、lifecycle、lifecycle-boundary、queue、regression、ui、qml(1x 8/8) 全部 PASS;新增 `mp4-pgs-skip`、`mkv-pgs-trim-skip`(全部策略:成功导出、PGS 被跳过、结果消息含“未保留”)及改为手动选择的 `mp4-pgs-reject`、`mkv-pgs-trim-reject`(明确失败、无正式文件)PASS。diff --git a/docs/EXPORT_PAGE_OPTIMIZATION_PLAN_2026-10-02.md b/docs/EXPORT_PAGE_OPTIMIZATION_PLAN_2026-10-02.mdnew file mode 100644index 00000000..c9c67918--- /dev/null+++ b/docs/EXPORT_PAGE_OPTIMIZATION_PLAN_2026-10-02.md@@ -0,0 +1,159 @@+# Veyra 导出页面与批量导出优化方案++> 本文保留最初研究时的判断;“尚未实现/下一步”指研究阶段。随后用户已授权目标模式实施,最终实现、验收和限制见 [执行记录](EXPORT_PAGE_EXECUTION_2026-10-02.md)。++本方案针对用户提供的导出页截图和四项需求:控件越界、可整理的多文件队列、多音轨与内嵌字幕保留、取消后重新导出,以及成功提示音。建议先修任务退出和重试,再接可编辑队列,最后补齐封装与轨道保留。现有独立导出 worker 和增强链继续复用。++研究日期:2026-10-02。当前交付是研究方案,尚未修改产品代码或完成 Veyra 导出验收。++## 工作区和协作边界++- 已从本地 `main` 固定提交 `09392c4d66b267cc75269b068aaffe3189830d37` 创建分支 `codex/export-page-20261002`。+- 独立源码目录:`E:/项目/Veyra/worktrees/export-page-20261002`。+- 本轮只新增本方案、更新该工作区的 `docs/WORKLOG.md`;研究日志和样本在 `E:/项目/Veyra/{logs,tests,tmp}/export-page-20261002/`。+- 桌面 checkout 保持旧迁移分支及其未提交内容。没有切换、stash、reset、清理或写入 Claude 的工作区,也没有改动既有分支指针。+- `codex/xbox-20261001`、`codex/moonlight-20261001` 的已提交内容都涉及 `QmlPlayerBridge.cpp/.h` 和 `CMakeLists.txt`。独立 worktree 避免运行时相互覆盖,但不能保证未来合并没有冲突。实施时只改导出相关函数,新增队列和封装逻辑放到职责明确的文件,避免整文件格式化;未来按函数核对并合并。+- 本轮不启动 Veyra、GPU 导出或共享构建,不占用 Claude 的候选目录、用户配置或运行中的程序。后续构建、测试、TEMP/TMP、日志、测试配置均使用本任务专用 E 盘目录。+- 这不是继续旧桌面 QML migration 无人值守任务。旧 guard 固定桌面目录、旧分支和 `main=df41580`,不能用来证明本任务隔离;本轮未运行或修改它。后续实施前基于本分支建立独立文件范围和哈希记录,不改旧 baseline。本方案明确列出后端依赖,不把它们算成纯 UI 修改。+- 未 commit、merge、push 或发布;未修改 AGENTS、SDK、运行库、用户文件。++## 源码确认的现状++以下行号对应上述固定提交,后续改动后应以符号为准。++| 项目 | 源码证据 | 判断 |+|---|---|---|+| 分辨率选项越界 | `qml/Veyra/ExportPage.qml:226` 右栏固定 330;`:297` 一行塞入 8 个分辨率选项。`VSeg.qml` 按每个按钮的文字宽度加 20 计算固有宽度;`VRow.qml` 按子项宽度给控件槽分配空间 | 与截图一致的布局约束冲突。右栏两级边距后约剩 278 逻辑像素,还需放标签和间距;不能靠裁切或缩小文字解决 |+| 大队列和短窗口 | `ExportPage.qml:136` 左栏是 ColumnLayout + Repeater,右栏 `:232` 也是固定高度的 ColumnLayout | 缺少列表虚拟化和纵向滚动;增加文件和轨道设置会放大问题 |+| 视频区域单独计算 | `qml/Veyra/Main.qml:190` 重复写死 250/330 两栏及底部 120 高度,实际 trim 卡为 92 | 导出页布局改变必须同步原生视频区域,不能只改可见 QML 卡片 |+| 添加即执行 | `QmlPlayerBridge.cpp:4539` 选文件后立刻问输出目录,再逐项 enqueue;`ExportJobManager.cpp:108` 空闲时 enqueue 立即 start | 已有串行执行基础,但没有“先整理、后启动”的待处理列表 |+| 队列不可编辑 | `ExportPage.qml:169` 队列行没有点击预览、删除或拖排处理;`QmlPlayerBridge.cpp:5339` 只能清除已结束记录 | 需要队列模型和真实任务操作接口 |+| 状态映射不可靠 | `QmlPlayerBridge.cpp:3424` 按输出路径匹配行,并将“不再是当前任务”的 running 行推为 done | 重试、重名和连续失败时可能串状态;成功提示音不能依赖这套推断 |+| 取消后同名重试失败 | `VideoExportJob.cpp:287` 保留 partial;`ExportJobManager.cpp:81` 和 `VideoExportJob.cpp:26` 拒绝同名 partial;`QmlPlayerBridge.cpp:4027` 隐藏具体启动失败原因 | 可由代码直接确认的失败路径;尚无本轮用户错误日志,不能断言它是用户遇到的唯一原因 |+| 退出回收竞态 | worker 在 `ExportJobManager.cpp:166` 先发布终态再退出;父进程只有 `:126–134` 观察到进程退出才清理 shared;bridge 的 `:803` 只在 active/queued 时轮询,start 的 `:74` 又拒绝残留 shared | 静态确认存在窗口:UI 提前看到终态并停轮询,之后一直 busy。发生概率及是否命中本次反馈尚待受控复现 |+| 封装和轨道限制 | `VideoExportJob.cpp:136` 写死 mp4;`:154–172` 只复制一个 audio stream,没有 subtitle/attachment 映射;文件选择器与批量命名固定 mp4 | MKV、全部音轨和内嵌字幕需要真实封装改造,仅增加下拉框无效 |+| 预览影响剪辑设置 | `QmlPlayerBridge.cpp:3651` 的 openPath 会清空全局 trim | 每项剪辑与轨道选择必须独立保存,点击其他文件不能丢失前一项设置 |++历史 P4 测试证明过局部暂停、取消和顺序导出,但没有证明“取消后同路径重新开始”。本轮不把历史通过当成这个问题已经解决。++## 页面和队列交互++保留现有深色三栏结构:左侧管理文件,中间预览与入出点,右侧设置与开始操作。++| 区域 | 拟定行为 |+|---|---|+| 左侧顶部 | “文件队列 N”及“添加文件”;支持多选和拖入文件。添加只登记文件和异步读取信息,不导出、不弹输出目录,也不强制切走正在预览的文件 |+| 左侧列表 | 可滚动、虚拟化的 ListView;显示拖动柄、缩略图、文件名、时长、状态与删除按钮。单击文件选中并在中间预览;预览选择与执行中的任务分别标识 |+| 列表管理 | 空闲时可单项移除、清空列表、拖动排序;这些操作只移除记录。运行中可调整等待项;当前任务锁定,需先取消再移除。“清空队列”在运行时改为“清空等待” |+| 中间 | 显示所选文件,入点/出点归属于该文件。新增文件默认整片;切换预览时保存并恢复该项范围。预览另一文件不更改已经提交的导出输入和参数 |+| 右侧 | 分开呈现封装、视频编码、输出尺寸、质量、增强预设、音轨、字幕、保存目录。分辨率的 8 段按钮改成现有风格的下拉选择;多轨选项单独占行 |+| 右侧底部 | 进度、当前第几项、当前任务状态和“开始导出 N 项”固定在底部;上方设置区纵向滚动。CQ 显示恒定质量,避免同时把无效 Mbps 展示为正在使用的码率 |++正常窗口沿用三栏。低于三栏可用宽度时建议改为导出页内部“文件 / 预览 / 设置”切换,底部任务状态仍可达;不通过修改全局最小窗口尺寸掩盖布局问题。现有主窗口允许 720×260,验收必须覆盖这个下限及常用窗口、100%/125%/150%/200% DPI。控件尺寸采用明确的布局约束,依据 [Qt Quick 布局说明](https://doc.qt.io/qt-6/qtquicklayouts-overview.html)核对 implicit size、minimum size 和可分配空间。++导出页和 `Main.qml` 的原生视频区域使用同一份导出布局尺寸/断点计算,初始化时提供确定的非零矩形;隐藏预览时同步隐藏对应视频区域。保留单一 videoHost。验证切页、打开文件首帧和 DPI 切换,防止视频覆盖按钮或出现 1×1 交换链。++### 队列执行规则++1. 点击开始时才确定输出目录、预检文件并冻结本批设置。增强预设、编码/封装/质量为批次默认值;每项保存自己的剪辑范围和轨道选择。导出中修改预览设置不改变本批任务。+2. 一次只运行一个导出 worker,按列表顺序逐项完成。继续复用既有 worker 隔离和增强图,不创建多套 NGX 或多个并行 GPU 导出。+3. 每项有稳定 itemId,每次尝试有独立 jobId,整批有 batchId。结果按 ID 归属;模型存储输入、输出、设置快照、状态、错误和进度,不按文件名猜状态。+4. Qt 列表只是任务模型的呈现。扩展现有 ExportJobManager 的队列管理与事件,避免 QML 维护一套顺序、C++ deque 又维护另一套顺序。使用 QAbstractListModel 适配任务模型,拖排按 ID 和插入位置完成。+5. 新增的待处理列表不能继续直接调用旧的“空闲即启动”enqueue。提供明确 add/startBatch/move/remove/clearWaiting/retry 接口;原调用方兼容包装只保留已有语义,不顺手改旧 Win32 行为。+6. 文件级失败标为失败并保留原因,继续后续文件;目标目录整体不可写、磁盘满等批次级问题停止调度,保留等待项。失败项由“重试”重新置为待处理,避免自动无限重试。+7. 点击取消停止本批自动调度、取消当前项并保留等待项。回收完成后再点开始,会从取消项重新编码,然后处理等待项;成功项跳过。暂停/继续仅保留当前进程,不与取消后从头重试混用。+8. 开始时冻结当前批次成员;运行中新增文件作为下一批待处理项,不偷偷加入当前批次。允许调整本批尚未开始项目的先后;已开始项的输入/参数不变。+9. 默认输出采用 `<原名>_veyra.<容器>`;同名文件、不同目录同名源、与输入同路径等在启动前解决并展示目标。预留名称且最终落盘不覆盖已有文件;多实例竞争要报告真实冲突。++本轮视频队列覆盖上述完整流程。图片模式保留现有单帧/批量图片入口并补完成提醒;混合视频与图片的一套执行队列不列入本次视频队列改造。++## 封装与音轨字幕++**MKV 是封装,不是编码。** 界面应为“封装:MP4 / MKV”和“视频编码:H.264 / HEVC”。MP4 可以包含多音轨和兼容的内嵌字幕;不能把多轨能力宣传成 MKV 独有。需要保留电影的原始音轨及复杂字幕时优先推荐 MKV。[FFmpeg 流映射说明](https://ffmpeg.org/ffmpeg.html#Stream-selection)、[Matroska 编码映射](https://www.matroska.org/technical/codec_specs.html)。++| 设置 | 方案 |+|---|---|+| 音轨 | “保留全部 / 选择轨道 / 不保留”,新任务建议保留全部;预览只播放当前选中的一条音轨,不能把预览选择误当导出筛选 |+| 内嵌字幕 | “保留全部 / 选择轨道 / 不保留”;默认保留建议与容器兼容预检一起呈现。独立可切换字幕轨保留,不增加字幕烧录流程 |+| MP4 | 兼容音轨可多条复制;兼容文本字幕可封装,部分输入需转为 mov_text。复杂 ASS 样式、PGS/VobSub 图片字幕不能承诺无损进入 MP4 |+| MKV | 优先复制兼容音轨、SRT、ASS/SSA、PGS 等轨道。保留 ASS 所需字体附件、轨道语言/标题、default/forced 标记。目标是兼容轨道的完整保留,不承诺任意 codec 都能直接复制 |+| 不兼容 | 开始前逐轨给出“复制 / 需转换 / 不支持”。明确建议切换 MKV或排除此轨;不能静默丢轨、降混、烧录或转码。用户明确选 MP4 时不能暗中更换扩展名 |++MKV 对部分 MP4 字幕如 mov_text 也未必支持直接 packet copy,必须按实际输入判断。字幕转换复用已有 FFmpeg 编解码能力并标明转换后的格式;复杂样式不能保真时推荐保留原兼容容器或明确提示。字体附件原样封装,不安装到系统、不执行附件。Matroska 的 ASS、PGS 与字体附件映射见[官方定义](https://www.matroska.org/technical/codec_specs.html#s_textass)。++### 后端实现++- 给导出作业增加 container、audioPolicy、subtitlePolicy 与所选轨道描述。映射到 FFmpeg 的 mp4/matroska muxer;不能只换文件后缀。worker 的 Shared 协议升级版本并验证字段,不能直接跨进程复制含指针的容器对象。“全部”在 worker 枚举全部适用流,不设一个隐含条数上限截断音轨。+- 将单 audioIndex/audioStream 改成明确的输入流到输出流映射。视频仍走现有 GPU 增强与 NVENC/MF 编码;音频、字幕、附件沿用 FFmpeg 库的压缩包处理。不接 raw video pipe、不增加常态 GPU 像素回读,不重新实现容器格式。+- 输出保留支持的轨道 codec 参数、声道布局、语言、标题和标记;AAC/AC3/EAC3/DTS/TrueHD/FLAC/PCM 等是否可复制按实际 muxer 和本机版本预检,不以“支持 MKV”代替逐轨兼容判断。+- 无剪辑时尽量原样复制附属轨道;剪辑时视频、所有音轨、字幕共用同一源时间基准并统一平移时间戳。原有声音偏移保持,不能把每条音轨各自强行归零。音频直接复制存在包边界精度,不宣称任意采样点精确裁切。+- 跨越入点的文字字幕需要保留并裁剪有效时段,不能因开始时间早于入点就整条丢弃;字幕末尾不得超出剪辑区间。PGS/VobSub 等还需保留解码初始化/显示状态并验证入点画面,不能把它们当成普通 SRT 包减时间戳。缺少可靠裁剪路径时在预检明确拒绝该组合,不能标整项验收完成。+- 复用 FFmpeg interleaved mux,设置有界缓冲;稀疏字幕不能阻塞音频输出,不把整段音轨或字幕提前读入无限队列。用短样本、长间隔字幕和长音轨分别验收。+- 复用现有 HDR/颜色与增强合同,不在本任务扩大 Dolby Vision、补帧后端或新视频编码支持;节点链离线导出仍按当前实际支持边界提示。++### 本轮实际做过的容器验证++使用系统 FFmpeg `8.1.1-full_build-www.gyan.dev`,生成独立两秒 64×64、10 fps、两条 AAC 音轨和两条字幕的样本。只使用 CPU,没有调用 Veyra 或 NVIDIA runtime,也没有替换项目要求的 patched FFmpeg。++| 文件 | ffprobe 视频帧数 | 音轨数 | 字幕数及格式 |+|---|---:|---:|---|+| `E:/项目/Veyra/tests/export-page-20261002/container-probe/multi.mp4` | 20 | 2 | 2 × mov_text |+| `E:/项目/Veyra/tests/export-page-20261002/container-probe/multi.mkv` | 20 | 2 | 2 × subrip |++生成命令的完整参数、工具路径与结果保存在 `E:/项目/Veyra/logs/export-page-20261002/container-probe/result.json`;独立执行了 `ffprobe -v error -count_frames -show_streams -show_format -of json <样本>`,原始报告为同目录 `mp4-streams.json`、`mkv-streams.json`。两次生成和两次探测均 exit 0。++这证明封装本身可以多音轨/多字幕,不证明 Veyra 已实现,也不证明 ASS 字体、PGS、剪辑或音画同步已验收。++## 取消和重新导出++这部分先做,因为不稳定的单任务生命周期会破坏批量队列。++1. 增加“取消中/等待回收”状态,期间不能启动新 worker。停止新帧提交,按现有顺序停止编码、关闭封装、释放文件和 GPU 资源;保留当前有界退出超时及只针对本任务 Job Object 的兜底。+2. 区分“worker 报告了结果”和“进程已退出、父进程已回收”。只要进程或 IPC 句柄仍需处理,UI 调度就继续 poll;shared 终态不能单独关停轮询。最终终态由管理器在退出回收后发布,start 也应防御性回收已退出进程。+3. 每次尝试使用专属临时输出名,如 `.片名.veyra-<jobId>.partial`,并记录所属任务。失败/取消后只能清理自己创建的文件,且必须等 worker 退出、文件关闭。清理失败保留准确路径和原因,但不让历史 partial 永久阻塞新的尝试。+4. 既有同名 partial、其他任务 partial、源文件和已成功文件全部保留;不全目录扫描删除。开始下一次时创建新临时文件,成功关闭 mux 后再安全改为正式名,目标已存在则拒绝覆盖。+5. 启动失败立即读取/返回具体原因并通知界面,例如目标冲突、设置错误、设备错误;不再统一替换成“详见诊断”。任务行保留错误及对应日志路径。+6. 重试创建新的 jobId、cancel/pause 标志、计时和进度,不复用旧通信状态。取消发生在保存正式文件附近时,以实际安全落盘结果定义最终状态,不能出现已经成功却被删除或失败却播成功音。++本轮未运行原程序复现这个竞态,也未执行重试修复;上述结论分为已确认代码路径与待验证的竞态触发,不能写成“已修复”。++## 完成提示音++- 默认建议开启,提供“完成提示音”开关。使用 Windows 现成系统提示音 `MessageBeep(MB_OK)`,不引入新的媒体播放库。[Microsoft 接口说明](https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-messagebeep)。+- 单文件导出成功响一次;批量全部成功后响一次,不在每个文件结束时连续响。已有图片批量入口在确认全部完成后采用相同通知规则。+- 依据管理器已回收后的真实成功事件,以 batchId/jobId 去重;不能监听 exportRunning 从 true 变 false 就播放,因为失败、取消也会产生同样变化。+- 部分失败显示成功/失败数量,不播全成功提示音。取消、失败、空队列和清空队列均不播。+- 声音调用异步、不阻塞 UI;由系统声音设置决定是否可闻,仍保留可见完成提示。开关关闭后不得触发声音。++## 实施切片和验收++| 顺序 | 最小交付 | 必须验证的行为 |+|---|---|---|+| 1 | 取消、回收、临时文件及具体错误 | 同一路径开始→取消→再次开始,多轮成功;准备/编码/暂停/收尾期间取消;共享终态先于进程退出;清理失败;已有正式文件与其他任务 partial 不变 |+| 2 | 页面布局与文件队列 | 添加至少 20 个文件不启动 worker;点击预览、单项移除、清空、拖排;A/B/C 改 C/A/B 后实际按此顺序输出;等待项编辑与当前任务互不串状态;切换文件保留各自 trim |+| 3 | MKV 与附属轨道 | MP4/MKV × H.264/HEVC;无音轨、双音轨、多声道、多个字幕;ASS 字体、PGS、语言和 default/forced;容器不兼容明确提示;剪辑前后 A/V 和字幕时间、跨入点字幕正确 |+| 4 | 完成提示与合并回归 | 单个/整批成功仅一个成功事件;取消/失败/混合结果不播成功音;关闭提示音有效;播放与导出并行不改当前任务配置 |++页面检查覆盖 720×260、1280×720、1366×768、1920×1080 和不同 DPI;除静态截图外,还检查菜单可达、列表滚动、拖动命中、视频区域遮挡和错误长文本。不能用 clip=true 把超出部分藏掉算通过。++测试分为无需 GPU 的队列/状态测试、QML 交互测试、真实短片导出及 ffprobe/重放检查。取消竞态用受控 worker 在发布终态后延迟退出的方式稳定复现;不用反复碰运气。轨道完整性检查数量、codec、语言、标记、声道、内容和时间戳,不只检查文件存在或 exit 0。每个测试最多 300 秒;真实 NVIDIA Create/Evaluate、编码错误和未测硬件单独记录。++预期触及文件:++- `qml/Veyra/ExportPage.qml`、`qml/Veyra/Main.qml` 的导出布局分支及按需新增的导出组件;公共 VRow/VSeg 先不全局改版。+- `src/ui/QmlPlayerBridge.cpp`、`include/veyra/ui/QmlPlayerBridge.h` 的导出接口、轮询和通知,按需新增队列模型适配文件。+- `src/engine/ExportJobManager.cpp`、`include/veyra/engine/ExportJobManager.h`、`src/engine/VideoExportJob.cpp` 及导出参数头;多流封装可拆为独立导出 helper。+- `include/veyra/engine/EngineController.h` 当前承载 PlayerOptions,只按需扩展导出用字段;不扩改播放器、采集或声音时钟。+- 定向 unit/QML/integration 测试;新增编译单元时才最小修改 `CMakeLists.txt`。每个切片开工前固定实际文件清单。++后端上述接点属于本次后续实现的必要范围,当前仍只给方案。增强算法、shader、运行库、旧 Win32、Claude 的串流分支及与本次无关的解码/采集链路不包含在改造里。++## 审查结论和下一步++方案复用已有 worker、FFmpeg 与 Qt 组件,主要工作是把“文件清单、任务执行、预览选择”分清并建立可核对的结果归属。最大风险是取消回收竞态和带剪辑的字幕/多轨时间处理,工作量高于移动按钮或加 MKV 下拉框。++已做源码反向核对:没有把 MKV 当编码;没有把系统 FFmpeg 样本当产品通过;没有把“进程报告完成”当成“资源已回收”;没有用文件名或列表切换推断成功;没有把工作区隔离等同于未来无合并冲突。++下一步实施先建立本分支独立范围记录,稳定复现取消后的同路径重试与退出竞态,完成切片 1 后再接批量队列。本轮产品构建、QML 截图回归、真实 GPU 导出、提示音试听全部未执行。++研究收尾检查:`git diff --check` 通过;原桌面工作区 status 清单无变化,既有分支指针无变化,唯一新增引用是本任务分支。证据为 `E:/项目/Veyra/logs/export-page-20261002/isolation-check.json`。当前变更仅本方案和该工作区 WORKLOG。diff --git a/docs/WORKLOG.md b/docs/WORKLOG.mdindex adf6dbad..5ff74328 100644--- a/docs/WORKLOG.md+++ b/docs/WORKLOG.md@@ -1,5 +1,26 @@# Veyra 工作记录+## 2026-10-02 导出页面优化实施与本机验收++- 用户追加“开启目标模式搞定他”,在 `codex/export-page-20261002` / `E:/项目/Veyra/worktrees/export-page-20261002` 完成页面越界修复、左侧可整理批量队列、MKV/多音轨/内嵌字幕、取消重试与成功提示音。独立 ExportQueue、QmlExportQueueModel、ExportStreams 复用现有 worker/GPU 导出;未修改其他工作区、增强算法、运行库或旧 Win32。+- 每轮 `python -B scripts/acceptance/export-page-control.py` PASS,1109 文件不可变基线 SHA256 `d135f9ad55aacddc3ca5cf6f0771991b863306ebb5931d6e00c0a5aac9d4daae`。构建命令 `python -B scripts/acceptance/export-page-build.py <唯一日志名> <目标>`,最终 QML app/相关测试可构建;日志 `E:/项目/Veyra/logs/export-page-20261002/build-{final-review-001,boundary-fix-001,boundary-test-001}.log`。+- 定向驱动 `python -B scripts/acceptance/export-page-tests.py <模式> <标识> [素材]`:准备/暂停/编码/收尾取消、占用清理失败、旧 partial 保留和重试通过;实际 C/A/B 顺序、冻结成员和逐文件剪辑通过。MP4/MKV×H.264/HEVC、双轨/65轨/5.1/无音轨、文本转换/剪辑、ASS 字体、PGS 整片复制通过。内容校验修复 AAC priming 重复扣除;不支持压缩 PGS 不再假成功。图片字幕剪辑明确拒绝,不计为支持。+- 实际产品联动见 `production-ui-final-001.log`:视频与图片批次成功各一次系统声音调用,失败/取消/混合结果不响,静音偏好保存有效。QML 29/29、四种尺寸与 100/125/150/200% 缩放通过;颜色导出链 11/11、数据目录/曲线回归通过。实机为 RTX5070 NVENC;不冒称跨硬件、NR/SR/FG 或人工听音验收。+- 可运行版本 `E:/项目/Veyra/test-packages/export-page-20261002/veyra_qml_ui.exe`;构建在 `E:/项目/Veyra/build/export-page-20261002`;媒体/输出/截图/profile 在同任务 tests;日志在同任务 logs;TEMP/TMP 在同任务 tmp,stage 临时目录 `E:/项目/Veyra/tmp/ui-migration-stage/{baseline-app,candidate-ui-001,export-page-20261002}`。源码增量归档 `E:/项目/Veyra/archives/export-page-20261002-final`;包内无测试媒体/用户数据,SDK/runtime 不进源码 Git。+- 全部证据、失败修复和限制见 `docs/EXPORT_PAGE_EXECUTION_2026-10-02.md`。最终 exe 与构建哈希相同,52 份 QML 源文件一致,测试注入已移除。中间 staging 删除被自动审批以 `blocked by policy` 拒绝,未执行;三个中间目录及日志保留,见 `cleanup-deferred.json`。最终包/构建/验收证据保留,没有 commit/tag/merge/push/Release。++## 2026-10-02 导出页面优化研究与独立分支++- 用户要求另开分支研究导出页越界、左侧多文件可编辑队列、多音轨/内嵌字幕及 MKV、取消后无法再次导出、完成提示音,并避免影响 Claude 的其他分支。本轮交付方案,没有修改产品实现。+- 从本地 main `09392c4d66b267cc75269b068aaffe3189830d37` 执行 `git worktree add -b codex/export-page-20261002 E:/项目/Veyra/worktrees/export-page-20261002 09392c4d66b267cc75269b068aaffe3189830d37`,独立工作区建立成功。原桌面 checkout、其他工作区和既有分支均未写入;没有 stash/reset/切换其他分支或终止其他任务进程。开工状态和引用记录在 `E:/项目/Veyra/logs/export-page-20261002/` 的 `original-status-before.txt`、`branches-before.txt`、`worktrees-before.txt`、`research-baseline.json`。+- 阅读 README、AGENTS、产品规格、竞品审计、UI migration 三份历史方案、相关阶段 WORKLOG 及导出源码;确认当前 main 已合入 2.0.0,旧桌面 guard 固定历史 main/目录,不作为本次研究或新分支保护证明。旧 guard/baseline/AGENTS 没有修改,本轮不是旧无人值守轮次。+- 静态确认:330px 右栏内 8 段分辨率控件固有宽度与标签冲突;左右栏缺滚动;Main.qml 另写死原生视频位置;添加文件立即 enqueue/start;队列只镜像状态且缺预览/移除/拖排;导出写死 mp4、单条音轨且无字幕映射。取消保留 partial 与同名拒绝检查直接冲突;另识别 worker 提前发布终态、bridge 停轮询导致 shared 未回收的竞态窗口,未动态复现,不声称是唯一根因或已经修复。+- 独立容器试验:系统 FFmpeg 8.1.1 生成两秒 64×64 10fps 的 MP4/MKV,小样本均含 20 视频帧、2 条 AAC 音轨和 2 条内嵌字幕,MP4 为 mov_text、MKV 为 subrip。生成及 `ffprobe -v error -count_frames -show_streams -show_format -of json <file>` 均 exit 0;完整参数和报告在 `E:/项目/Veyra/logs/export-page-20261002/container-probe/`。样本在 `E:/项目/Veyra/tests/export-page-20261002/container-probe/`,TEMP/TMP 只对子进程设为 `E:/项目/Veyra/tmp/export-page-20261002/container-probe/`。这不是 Veyra 导出验收,也未替换项目 patched FFmpeg。+- 新增 `docs/EXPORT_PAGE_OPTIMIZATION_PLAN_2026-10-02.md`,给出交互语义、稳定任务 ID、逐项冻结配置、MKV/多音轨/字幕接口、专属临时文件和进程回收、批次成功提示音、四个实施切片与验收矩阵。研究引用 FFmpeg、Matroska、Qt、Microsoft 官方资料,无第三方实现搬运。+- 已识别未来冲突面:Xbox/Moonlight 已提交内容也涉及 QmlPlayerBridge 与 CMake;计划将新增队列/封装职责独立,并限制 bridge 为导出接点。没有修改、提交或合并 Claude 的内容。+- 收尾:`git diff --check` 通过,工作区只变更本方案和 WORKLOG;引用前后比对仅增加本任务分支,原桌面 status 清单无变化,main 仍为 `09392c4`。证据 `E:/项目/Veyra/logs/export-page-20261002/isolation-check.json`。这不是其他工作区内容逐字节审计,未据此冒称 Claude 的文件未自行变化。+- 未执行:产品构建、真实 NVIDIA runtime/Create/Evaluate、取消重试复现、QML/DPI/拖排交互、ASS/PGS/字体/剪辑验收及提示音试听。保留轻量研究样本与日志作为证据,没有生成打包或解压副本。下一步为方案中的切片 1;没有 commit/tag/merge/push/Release。+## 2026-10-01 2.0.0 合并 main 与分支整理- 用户授权(“基本上 2.0.0 已经没啥问题了……先合并一手,存档一下,更新更新文档,对齐目前进度”):整理 2.0.0 各分支并合并到**本地** `main`;不含 push / Release / 删旧 UI / 删 worktree。diff --git a/include/veyra/engine/EngineController.h b/include/veyra/engine/EngineController.hindex 4f5e1726..4aa0b2e8 100644--- a/include/veyra/engine/EngineController.h+++ b/include/veyra/engine/EngineController.h@@ -15,6 +15,7 @@#include "veyra/remoteplay/SessionInbox.h"#include "veyra/media/AudioTrack.h"#include "veyra/sink/VideoEncoder.h"+#include "veyra/engine/ExportOptions.h"namespace veyra::source { struct RemotePlayConnectDesc; class RemotePlaySessionSource; }namespace veyra::remoteplay { struct ControllerState;struct ControllerFeedback; }namespace veyra::sink { struct RgbaImage; }@@ -27,6 +28,8 @@ struct PlayerOptions { bool nr=false,sr=false,fg=false,realtime=true; uint32_t fdouble exportStartSeconds=0.0; // export-only trim; first complete frame at/after this timedouble exportEndSeconds=0.0; // export-only trim; 0 means source endsink::ExportRateControl exportRateControl=sink::ExportRateControl::Cq;+ ExportMediaOptions exportMedia;+ std::wstring exportTemporaryPath; // owned, uniquely reserved by this attemptbool 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 CPUdiff --git a/include/veyra/engine/ExportJobManager.h b/include/veyra/engine/ExportJobManager.hindex 8b218213..c4a0d148 100644--- a/include/veyra/engine/ExportJobManager.h+++ b/include/veyra/engine/ExportJobManager.h@@ -3,13 +3,13 @@#include <memory>#include <vector>namespace veyra::engine {-enum class ExportState { Idle, Preparing, Running, Paused, Finishing, Succeeded, Failed, Cancelled };+enum class ExportState { Idle, Preparing, Running, Paused, Finishing, Cancelling, Succeeded, Failed, Cancelled };struct ExportJobSnapshot {ExportState state=ExportState::Idle;double progress=0;uint64_t jobId=0,frozenRevision=0,sourceFrames=0,generated=0,holds=0,encoded=0;EnhancementSettings frozen;- std::wstring message,output,workerLog;+ std::wstring message,output,workerLog,temporaryPath;uint32_t workerPid=0;double etaSeconds=0;uint64_t queuePosition=0,queued=0;@@ -18,14 +18,14 @@ struct ExportJobSnapshot {// never skipped silently. Reset when a fresh export starts from idle.uint64_t queueFailures=0;std::wstring lastQueueFailure;- bool active()const{return state>=ExportState::Preparing&&state<=ExportState::Finishing;}+ bool active()const{return state>=ExportState::Preparing&&state<=ExportState::Cancelling;}};// One isolated NGX context in a child process. Anonymous inherited mapping is// the entire IPC capability; no discoverable pipe, shell or config pathname.class ExportJobManager {public:ExportJobManager();~ExportJobManager();- bool start(const std::wstring&,const std::wstring&,EnhancementSettings,bool hevc,unsigned maxFrames=0,int audioStreamIndex=-1,double trimStartSeconds=0.0,double trimEndSeconds=0.0,sink::ExportRateControl rateControl=sink::ExportRateControl::Cq);+ bool start(const std::wstring&,const std::wstring&,EnhancementSettings,bool hevc,unsigned maxFrames=0,int audioStreamIndex=-1,double trimStartSeconds=0.0,double trimEndSeconds=0.0,sink::ExportRateControl rateControl=sink::ExportRateControl::Cq,ExportMediaOptions media={});bool enqueue(const std::wstring&,const std::wstring&,EnhancementSettings,bool hevc,unsigned maxFrames=0,int audioStreamIndex=-1,double trimStartSeconds=0.0,double trimEndSeconds=0.0,sink::ExportRateControl rateControl=sink::ExportRateControl::Cq);void clearQueue();size_t queuedCount() const;diff --git a/include/veyra/engine/ExportOptions.h b/include/veyra/engine/ExportOptions.hnew file mode 100644index 00000000..73bcb2ec--- /dev/null+++ b/include/veyra/engine/ExportOptions.h@@ -0,0 +1,39 @@+#pragma once+#include <array>+#include <cstdint>+#include <string>++namespace veyra::engine {+std::wstring reserveExportTemporaryFile(const std::wstring& output, std::wstring& error);+bool removeExportTemporaryFile(const std::wstring& path, std::wstring& error);+enum class ExportContainer : uint32_t { Mp4, Matroska };+enum class ExportTrackPolicy : uint32_t { Default, All, Selected, None };+// Fixed-size IPC representation. All enumerates the source without a track cap;+// only an explicit selection has a published limit (never silently truncated).+struct ExportTrackSelection {+ ExportTrackPolicy policy = ExportTrackPolicy::Default;+ uint32_t count = 0;+ std::array<int, 64> indices{};+ bool valid() const {+ if (policy > ExportTrackPolicy::None || count > indices.size()) return false;+ for (uint32_t i = 0; i < count; ++i) {+ if (indices[i] < 0) return false;+ for (uint32_t j = 0; j < i; ++j) if (indices[i] == indices[j]) return false;+ }+ return policy != ExportTrackPolicy::Selected || count > 0;+ }+ bool contains(int index) const {+ for (uint32_t i = 0; i < count; ++i) if (indices[i] == index) return true;+ return false;+ }+};+struct ExportMediaOptions {+ ExportContainer container = ExportContainer::Mp4;+ ExportTrackSelection audio;+ ExportTrackSelection subtitles{ExportTrackPolicy::None};+ // Text conversion is explicit. The UI reports it before start; bitmap+ // subtitles and incompatible audio are never silently dropped/transcoded.+ bool convertTextSubtitles = true;+ bool valid() const { return container <= ExportContainer::Matroska && audio.valid() && subtitles.valid(); }+};+}diff --git a/include/veyra/engine/ExportQueue.h b/include/veyra/engine/ExportQueue.hnew file mode 100644index 00000000..348a5124--- /dev/null+++ b/include/veyra/engine/ExportQueue.h@@ -0,0 +1,59 @@+#pragma once+#include "veyra/engine/ExportJobManager.h"+#include "veyra/engine/ExportStreams.h"+#include <future>++namespace veyra::engine {+enum class ExportItemState { Ready, Queued, Running, Done, Failed, Cancelled };+struct ExportQueueItem {+ uint64_t id=0,batch=0,job=0,revision=1,inspected=0;+ std::wstring input,output,note;+ ExportItemState state=ExportItemState::Ready;+ double progress=0,start=0,end=0;+ ExportMediaOptions media;+ ExportMediaInfo info;+ EnhancementSettings frozen;+ bool hevc=false,explicitOutput=false;+ sink::ExportRateControl rate=sink::ExportRateControl::Cq;+};+// Sole order/state store for the QML queue. The existing manager remains the+// single-process executor; its legacy immediate-enqueue API is not used here.+class ExportQueue {+public:+ explicit ExportQueue(ExportJobManager& worker);+ ~ExportQueue();+ uint64_t add(const std::wstring& input,const std::wstring& output={});+ bool remove(uint64_t id);void clearWaiting();bool move(uint64_t id,int destination);+ bool retry(uint64_t id);+ bool setTrim(uint64_t id,double start,double end);+ bool setTracks(uint64_t id,bool audio,ExportTrackSelection selection);+ void setContainer(ExportContainer container);+ bool start(const std::wstring& directory,EnhancementSettings settings,bool hevc,sink::ExportRateControl rate,std::wstring& error);+ void cancel();bool tick();+ bool busy()const{return running_||snapshot_.active();}+ bool needsTick()const;+ size_t readyCount()const;+ const std::vector<ExportQueueItem>& items()const{return items_;}+ const ExportQueueItem* find(uint64_t id)const;+ const ExportJobSnapshot& snapshot()const{return snapshot_;}+ uint64_t successEvent()const{return successEvent_;}+ uint64_t batchId()const{return batch_;}+ unsigned successes()const{return successes_;}unsigned failures()const{return failures_;}+ const std::wstring& status()const{return status_;}+private:+ ExportQueueItem* mutableItem(uint64_t id);+ bool editable(const ExportQueueItem&)const;+ void finishBatch();+ ExportJobManager& worker_;+ std::vector<ExportQueueItem> items_;+ ExportJobSnapshot snapshot_;+ ExportContainer container_=ExportContainer::Mp4;+ uint64_t nextId_=0,batch_=0,active_=0,successEvent_=0;+ unsigned successes_=0,failures_=0;+ bool running_=false,interrupted_=false;+ std::wstring status_=L"添加文件后,点击开始导出",directory_;+ std::future<ExportMediaInfo> probe_;+ std::atomic<bool> stopProbe_{false};+ uint64_t probingId_=0,probingRevision_=0;+};+}diff --git a/include/veyra/engine/ExportStreams.h b/include/veyra/engine/ExportStreams.hnew file mode 100644index 00000000..9ba2113e--- /dev/null+++ b/include/veyra/engine/ExportStreams.h@@ -0,0 +1,39 @@+#pragma once+#include "veyra/engine/ExportOptions.h"+#include <atomic>+#include <memory>+#include <vector>+struct AVFormatContext;++namespace veyra::engine {+struct ExportTrackInfo {+ int index=-1,channels=0;+ bool audio=false,subtitle=false,selected=false,compatible=true,converted=false;+ bool defaultTrack=false,forced=false;+ std::string codec,language,title;+ std::wstring action;+};+struct ExportMediaInfo {+ double duration=0;+ std::vector<ExportTrackInfo> tracks;+ std::wstring error;+ // Tracks an "all tracks" policy could not carry into this container. They+ // are reported before start and in the result, never dropped silently.+ std::wstring skipped;+};+// Packet-only companion to the existing GPU video path. One demuxer, bounded+// lookahead, common video origin; text conversion uses libavcodec.+class ExportStreams {+public:+ ExportStreams();~ExportStreams();+ bool prepare(const std::wstring& input,AVFormatContext* output,const ExportMediaOptions& options,+ int defaultAudio,double start,double end,std::atomic<bool>& cancel,std::wstring& error);+ bool writeUntil(double seconds,double videoOrigin,bool final,std::wstring& error);+ const ExportMediaInfo& info()const;+ static ExportMediaInfo probe(const std::wstring& input,const ExportMediaOptions& options,+ double start,double end,std::atomic<bool>& cancel);+ static void enableWorkerLogging(bool detailed=false);+private:+ struct Impl;std::unique_ptr<Impl> p_;+};+}diff --git a/include/veyra/ui/QmlExportQueueModel.h b/include/veyra/ui/QmlExportQueueModel.hnew file mode 100644index 00000000..983c9f28--- /dev/null+++ b/include/veyra/ui/QmlExportQueueModel.h@@ -0,0 +1,35 @@+#pragma once+#include "veyra/engine/ExportQueue.h"+#include <QAbstractListModel>+#include <QStringList>++namespace veyra::ui {+class QmlExportQueueModel final:public QAbstractListModel {+ Q_OBJECT+ Q_PROPERTY(int count READ count NOTIFY changed)+ Q_PROPERTY(qulonglong selectedId READ selectedId WRITE setSelectedId NOTIFY changed)+public:+ enum Role {ItemId=Qt::UserRole+1,Name,Input,Output,State,Progress,Note,Duration,Current,Locked,Inspecting};+ explicit QmlExportQueueModel(engine::ExportJobManager& worker,QObject* parent=nullptr);+ int rowCount(const QModelIndex& parent={})const override;+ QVariant data(const QModelIndex& index,int role)const override;+ QHash<int,QByteArray> roleNames()const override;+ int count()const{return rowCount();}+ qulonglong selectedId()const{return selected_;}+ void setSelectedId(qulonglong id);+ Q_INVOKABLE qulonglong addFile(const QString& path,const QString& output={});+ Q_INVOKABLE bool removeItem(qulonglong id);+ Q_INVOKABLE bool moveItem(qulonglong id,int destination);+ Q_INVOKABLE bool retryItem(qulonglong id);+ Q_INVOKABLE void clearWaiting();+ Q_INVOKABLE QVariantMap get(int index)const;+ bool tick();void refresh();+ engine::ExportQueue& queue(){return queue_;}+ const engine::ExportQueue& queue()const{return queue_;}+signals:+ void changed();+private:+ engine::ExportQueue queue_;+ uint64_t selected_=0;+};+}diff --git a/include/veyra/ui/QmlPlayerBridge.h b/include/veyra/ui/QmlPlayerBridge.hindex 94a66571..a1cc7be0 100644--- a/include/veyra/ui/QmlPlayerBridge.h+++ b/include/veyra/ui/QmlPlayerBridge.h@@ -303,6 +303,14 @@ class QmlPlayerBridge : public QObject {Q_PROPERTY(bool colourCanPaste READ colourCanPaste NOTIFY settingsChanged)// Export queue rows: [{name, input, output, state, progress, note, current}].Q_PROPERTY(QVariantList exportItems READ exportItems NOTIFY exportChanged)+ Q_PROPERTY(QObject* exportQueueModel READ exportQueueModel CONSTANT)+ Q_PROPERTY(int exportContainer READ exportContainer WRITE setExportContainer NOTIFY exportChanged)+ Q_PROPERTY(int exportReadyCount READ exportReadyCount NOTIFY exportChanged)+ Q_PROPERTY(QVariantList exportTracks READ exportTracks NOTIFY exportChanged)+ Q_PROPERTY(int exportAudioPolicy READ exportAudioPolicy NOTIFY exportChanged)+ Q_PROPERTY(int exportSubtitlePolicy READ exportSubtitlePolicy NOTIFY exportChanged)+ Q_PROPERTY(bool exportSelectionEditable READ exportSelectionEditable NOTIFY exportChanged)+ Q_PROPERTY(bool exportCompletionSound READ exportCompletionSound WRITE setExportCompletionSound NOTIFY exportChanged)// Capture dialog preview: the session's poster still (the engine's own// first-frame poster), as a data URL; "" when the session has none. Never a// periodic readback: that would stall the live capture path.@@ -724,6 +732,18 @@ public:Q_INVOKABLE void colourCopy();Q_INVOKABLE bool colourPaste();QVariantList exportItems() const;+ QObject* exportQueueModel() const;+ int exportContainer() const;void setExportContainer(int value);+ int exportReadyCount() const;+ QVariantList exportTracks() const;+ int exportAudioPolicy() const;int exportSubtitlePolicy() const;+ bool exportSelectionEditable() const;+ bool exportCompletionSound() const;void setExportCompletionSound(bool enabled);+ Q_INVOKABLE void addExportFiles(const QStringList& paths);+ Q_INVOKABLE void addCurrentExportFile();+ Q_INVOKABLE void previewExportItem(qulonglong id);+ Q_INVOKABLE void setExportTrackPolicy(bool audio,int policy);+ Q_INVOKABLE void toggleExportTrack(bool audio,int index,bool keep);Q_INVOKABLE void clearFinishedExportItems();Q_INVOKABLE QString fileThumbnailId(const QString& path, double seconds) const;QString capturePreviewUrl() const;diff --git a/qml/Veyra/ExportLayout.js b/qml/Veyra/ExportLayout.jsnew file mode 100644index 00000000..70ef54d2--- /dev/null+++ b/qml/Veyra/ExportLayout.js@@ -0,0 +1,24 @@+.pragma library+// Logical pixels shared by the QML cards and the one native videoHost.+function calculate(width, height, tab) {+ const compact = width < 1120 || height < 500+ const margin = 12, top = 56, gap = 10+ const bodyHeight = Math.max(1, height - top - margin)+ const leftWidth = 260, rightWidth = 340+ const footerHeight = compact ? 60 : 116+ const body = { x: margin, y: top, width: Math.max(1, width - 2 * margin),+ height: Math.max(1, bodyHeight - footerHeight - gap) }+ const left = compact ? body : { x: margin, y: top, width: leftWidth, height: bodyHeight }+ const settings = compact ? body : { x: width - margin - rightWidth, y: top,+ width: rightWidth, height: bodyHeight - footerHeight - gap }+ const footer = { x: compact ? margin : settings.x, y: height - margin - footerHeight,+ width: compact ? body.width : rightWidth, height: footerHeight }+ const centerX = compact ? margin : margin + leftWidth + gap+ const centerWidth = compact ? body.width : Math.max(1, width - margin * 2 - leftWidth - rightWidth - gap * 2)+ const centerHeight = compact ? body.height : bodyHeight+ const trimHeight = compact ? 72 : 110+ const preview = { x: centerX, y: top, width: centerWidth, height: Math.max(1, centerHeight - trimHeight - gap) }+ const trim = { x: centerX, y: top + centerHeight - trimHeight, width: centerWidth, height: trimHeight }+ return { compact: compact, left: left, settings: settings, footer: footer, preview: preview, trim: trim,+ video: !compact || tab === 1 ? preview : { x: 0, y: 0, width: 0, height: 0 } }+}diff --git a/qml/Veyra/ExportPage.qml b/qml/Veyra/ExportPage.qmlindex 293b5edb..6ef8ce3d 100644--- a/qml/Veyra/ExportPage.qml+++ b/qml/Veyra/ExportPage.qml@@ -1,555 +1,346 @@-// 导出, rebuilt from the design (pages-b.js PAGES.exp + pages.css .exp).-//-// Design grid: 250px | 1fr | 330px, rows auto | 1fr | auto, padding 14. The queue-// card spans rows 2-3 on the left; the video sits in the middle with the trim range-// under it; output settings fill the right column.-//-// Scope: preset selection, codec, output size, rate control, queueing and-// progress are wired to the engine's export job. Queue execution is serialized-// by ExportJobManager; full multi-file cancellation/ordering acceptance remains-// a separate runtime check.import QtQuickimport QtQuick.Controls+import QtQuick.Controls.Basic as Basicimport QtQuick.Layouts+import "ExportLayout.js" as ExportLayoutVPage {id: rootsignal requestPage(string page)- // pages-b.js 类型: 视频 (the encoder settings) or 图片 (frame / batch).property string exportKind: "video"- readonly property var rows: veyra.exportItems- // The playing file is the first row unless the queue already carries it.- readonly property bool currentListed: rows.some(r => r.current)- function stateText(r) {- switch (r.state) {- case "running": return "导出中 " + (r.progress * 100).toFixed(0) + "%"- case "paused": return "已暂停 " + (r.progress * 100).toFixed(0) + "%"- case "queued": return "排队中"- case "done": return "已完成"- case "failed": return "失败" + (r.note.length > 0 ? ":" + r.note : "")- case "cancelled": return "已取消"- }- return r.state+ property int compactTab: 0+ readonly property var geometry: ExportLayout.calculate(width, height, compactTab)+ readonly property bool compact: geometry.compact+ property double draggedId: 0+ property int dropIndex: -1+ property real dragY: 0+ function stateText(state, progress, inspecting) {+ if (state === "ready") return inspecting ? "正在读取轨道…" : "待导出"+ if (state === "queued") return "等待导出"+ if (state === "running") return "导出中 " + (progress * 100).toFixed(0) + "%"+ return ({done: "已完成", failed: "失败 · 点击重试", cancelled: "已取消 · 可重新开始"})[state] || state+ }+ function preview(id) {+ if (compact) compactTab = 1+ Qt.callLater(() => veyra.previewExportItem(id))}- // .qitem: thumbnail, name, what it is / where it stands, progress.- component QueueItem: Rectangle {- id: qi- property string thumb: ""- property string name: ""- property string meta: ""- property real progress: 0- property bool showProgress: false- property bool selected: false- property bool failed: false+ component Note: Text {Layout.fillWidth: true- implicitHeight: 56- radius: 10- color: selected ? Qt.rgba(1, 1, 1, 0.06) : qiHover.hovered ? Qt.rgba(1, 1, 1, 0.04) : "transparent"- border.width: 1- border.color: selected ? Theme.stroke2 : "transparent"- HoverHandler { id: qiHover }- RowLayout {- anchors.fill: parent- anchors.margins: 7- spacing: 10- Rectangle {- implicitWidth: 64; implicitHeight: 40; radius: 7- color: Theme.videoBlack- clip: true- Image {- objectName: qi.objectName + "-image"- anchors.fill: parent- fillMode: Image.PreserveAspectCrop- asynchronous: true- source: qi.thumb- }+ wrapMode: Text.Wrap+ color: Theme.t3+ font.family: Theme.fontUi+ font.pixelSize: 11+ }+ component ExportScrollBar: Basic.ScrollBar {+ id: bar+ implicitWidth: 8+ padding: 2+ visible: size < 1+ contentItem: Rectangle { implicitWidth: 4; implicitHeight: 30; radius: 2; color: bar.pressed ? Theme.t2 : Theme.t3; opacity: bar.active || bar.hovered ? 0.9 : 0.45 }+ background: Item {}+ }+ // Export-only bounded menu: even at 720x260 every resolution is reachable.+ component Choice: Basic.ComboBox {+ id: choice+ property var options: []+ property string selected: ""+ signal picked(string id)+ model: options+ textRole: "label"+ valueRole: "id"+ currentIndex: Math.max(0, options.findIndex(o => String(o.id) === selected))+ implicitWidth: 172+ implicitHeight: 30+ onActivated: index => picked(String(options[index].id))+ background: Rectangle { radius: 8; color: Theme.card2; border.color: Theme.stroke2 }+ contentItem: Text { leftPadding: 10; rightPadding: 24; verticalAlignment: Text.AlignVCenter; text: choice.currentText; color: Theme.t1; elide: Text.ElideRight; font.family: Theme.fontUi; font.pixelSize: 12 }+ indicator: VIcon { x: choice.width - 22; y: 8; name: "down"; size: 14; color: Theme.t3 }+ popup: Popup {+ id: choicesPopup+ parent: Overlay.overlay+ width: choice.width+ height: Math.min(list.contentHeight + 8, Math.max(40, root.height - 16), 320)+ padding: 4+ onAboutToShow: {+ const point = choice.mapToItem(parent, 0, choice.height + 4)+ x = Math.max(8, Math.min(point.x, parent.width - width - 8))+ y = Math.max(8, Math.min(point.y, parent.height - height - 8))}- ColumnLayout {- Layout.fillWidth: true- spacing: 2- Text {- Layout.fillWidth: true- text: qi.name- color: Theme.t1- font.family: Theme.fontUi; font.pixelSize: 12; font.weight: Font.Medium- elide: Text.ElideMiddle- }- Text {- Layout.fillWidth: true- text: qi.meta- color: qi.failed ? Theme.err : Theme.t3- font.family: Theme.fontUi; font.pixelSize: 11- elide: Text.ElideRight- }- Rectangle {- visible: qi.showProgress- Layout.fillWidth: true- implicitHeight: 3- radius: 9- color: Qt.rgba(1, 1, 1, 0.08)- Rectangle {- width: parent.width * Math.max(0, Math.min(1, qi.progress))- height: parent.height; radius: 9- color: Theme.accent- Behavior on width { NumberAnimation { duration: Theme.d(300) } }- }+ background: Rectangle { radius: 8; color: Theme.card2; border.color: Theme.stroke2 }+ contentItem: ListView {+ id: list+ objectName: "videoCover"+ property real coverRadius: 8+ clip: true+ model: choice.options+ currentIndex: choice.currentIndex+ ScrollBar.vertical: ExportScrollBar {}+ delegate: Basic.ItemDelegate {+ required property var modelData+ required property int index+ width: list.width; height: 32+ enabled: modelData.disabled !== true+ highlighted: index === choice.currentIndex+ background: Rectangle { radius: 5; color: parent.highlighted ? Theme.card3 : "transparent" }+ contentItem: Text { text: modelData.label; color: Theme.t1; font.family: Theme.fontUi; font.pixelSize: 12; verticalAlignment: Text.AlignVCenter; elide: Text.ElideRight }+ onClicked: { choice.picked(String(modelData.id)); choicesPopup.close() }}}}}-- // --- header -----------------------------------------------------------RowLayout {id: head- anchors.left: parent.left- anchors.right: parent.right- anchors.top: parent.top- anchors.margins: 14- height: 32- spacing: 8+ x: 12; y: 12; width: parent.width - 24; height: 32+ spacing: 12VH2 { text: "导出" }- Text {- text: "按所选预设导出,导出期间可继续观看"- color: Theme.t3- font.family: Theme.fontUi- font.pixelSize: Theme.fsBody- }+ Text { visible: !root.compact; text: "先整理文件,再按顺序导出"; color: Theme.t3; font.family: Theme.fontUi; font.pixelSize: 12 }Item { Layout.fillWidth: true }- VButton { iconName: "plus"; text: "添加文件"; onClicked: veyra.addExportFilesDialog() }+ VSeg {+ objectName: "export-tabs"+ visible: root.compact+ options: [{id: "0", label: "文件"}, {id: "1", label: "预览"}, {id: "2", label: "设置"}]+ current: String(root.compactTab)+ onPicked: id => root.compactTab = Number(id)+ }}-- // --- left column: what is being exported ------------------------------Rectangle {id: queueCard- anchors.left: parent.left- anchors.leftMargin: 14- anchors.top: head.bottom- anchors.topMargin: 10- anchors.bottom: parent.bottom- anchors.bottomMargin: 14- width: 250- radius: Theme.rCard- color: Theme.card- border.width: 1- border.color: Theme.stroke-- ColumnLayout {- anchors.fill: parent- anchors.margins: 12- spacing: 8- RowLayout {- Layout.fillWidth: true- VEyebrow { text: "队列 · " + (root.rows.length + (root.currentListed || !veyra.hasSource ? 0 : 1)) }- Item { Layout.fillWidth: true }- VButton {- objectName: "export-clear-finished"- visible: root.rows.some(r => r.state !== "running" && r.state !== "queued" && r.state !== "paused")- ghost: true; implicitHeight: 24; text: "清除已结束"- onClicked: veyra.clearFinishedExportItems()- }- }- // The playing file, first, unless the queue already holds it.- QueueItem {- objectName: "export-item-thumb"- visible: veyra.hasSource && veyra.duration > 0 && !veyra.isCapture && !root.currentListed- selected: true- thumb: visible ? "image://veyra-thumb/" + veyra.thumbnailGeneration + "/" + Math.round(veyra.duration * 100) : ""- name: veyra.sourceName- meta: veyra.sourceRateText + " · " + veyra.durationText + " · 待导出"- }- Text {- visible: !veyra.hasSource && root.rows.length === 0- Layout.fillWidth: true- text: "未打开文件;可用“添加文件”直接排队"- color: Theme.t3- font.family: Theme.fontUi- font.pixelSize: 11- wrapMode: Text.WordWrap- }- Repeater {- model: root.rows- delegate: QueueItem {- required property var modelData- required property int index- objectName: "export-queue-row-" + index- selected: modelData.current- thumb: modelData.current- ? "image://veyra-thumb/" + veyra.thumbnailGeneration + "/" + Math.round(veyra.duration * 100)- : veyra.fileThumbnailId(modelData.input, 10)- name: modelData.name- meta: root.stateText(modelData)- failed: modelData.state === "failed"- showProgress: modelData.state !== "queued"- progress: modelData.progress- }- }- Rectangle { Layout.fillWidth: true; implicitHeight: 1; color: Theme.stroke }- Text {- visible: veyra.exportQueueCount > 0- Layout.fillWidth: true- text: "等待队列 " + veyra.exportQueueCount + " 项"- color: Theme.accent- font.family: Theme.fontMono- font.pixelSize: 11- }- Text {- objectName: "export-queue-failure"- visible: veyra.exportQueueFailures > 0- Layout.fillWidth: true- text: veyra.exportQueueFailures + " 项未能开始 · 最近:" + veyra.exportQueueFailure- color: Theme.err- font.family: Theme.fontUi- font.pixelSize: 11- wrapMode: Text.WordWrap- }- Text {- Layout.fillWidth: true- text: "按加入顺序逐项导出;每项独立保留 partial。"- color: Theme.t3- font.family: Theme.fontUi- font.pixelSize: 11- wrapMode: Text.WordWrap- }- Item { Layout.fillHeight: true }+ objectName: "export-queue-card"+ x: root.geometry.left.x; y: root.geometry.left.y+ width: root.geometry.left.width; height: root.geometry.left.height+ visible: !root.compact || root.compactTab === 0+ radius: Theme.rCard; color: Theme.card; border.color: Theme.stroke+ RowLayout {+ id: queueHead+ x: 10; y: 10; width: parent.width - 20; height: 30; spacing: 5+ Text { text: "队列 " + veyra.exportQueueModel.count; color: Theme.t2; font.family: Theme.fontUi; font.pixelSize: 12 }+ Item { Layout.fillWidth: true }+ VButton { objectName: "export-add-files"; text: "添加"; iconName: "plus"; onClicked: veyra.addExportFilesDialog() }+ VButton { objectName: "export-clear-queue"; ghost: true; text: veyra.exportRunning ? "清空等待" : "清空"; onClicked: veyra.exportQueueModel.clearWaiting() }}- }-- // --- right column ------------------------------------------------------ Rectangle {- id: rightCol- anchors.right: parent.right- anchors.rightMargin: 14- anchors.top: head.bottom- anchors.topMargin: 10- anchors.bottom: parent.bottom- anchors.bottomMargin: 14- width: 330- radius: Theme.rCard- color: Theme.card- border.width: 1- border.color: Theme.stroke-- ColumnLayout {- anchors.fill: parent- anchors.margins: 12- spacing: 4-- VH3 { text: "输出设置" }-- VRow {- label: "类型"- VSeg {- objectName: "export-kind"- options: [{ id: "video", label: "视频" }, { id: "image", label: "图片" }]- current: root.exportKind- onPicked: id => root.exportKind = id- }- }-- // 图片: each image runs through the player's list chain and the engine's- // own frame save (PNG, JXR for HDR output).- VGroup {- visible: root.exportKind === "image"- VRow {- label: "当前画面"- hint: "保存正在播放的这一帧"- hintBelow: true- VButton {- objectName: "export-frame"- text: "导出当前画面…"- enabled: veyra.hasSource && !veyra.imageBatchActive- onClicked: veyra.saveFrameDialog()- }- }- VRow {- label: "批量图片"- hint: "选择多张图片,按当前列表链逐张处理"- hintBelow: true- VButton {- objectName: "export-images"- text: veyra.imageBatchActive ? "取消批量" : "批量处理图片…"- onClicked: veyra.imageBatchActive ? veyra.cancelImageBatch() : veyra.exportImagesDialog()- }- }- Text {- objectName: "image-batch-status"- visible: veyra.imageBatchStatus.length > 0- Layout.fillWidth: true- Layout.bottomMargin: 8- text: veyra.imageBatchStatus- color: veyra.imageBatchFailures > 0 ? Theme.warn : Theme.t3- font.family: Theme.fontUi- font.pixelSize: 11- wrapMode: Text.WordWrap- }- }-- VGroup {- visible: root.exportKind === "video"- VRow {- label: "编码"- VSeg {- options: [{ id: "h264", label: "H.264" }, { id: "hevc", label: "HEVC" }]- current: veyra.exportHevc ? "hevc" : "h264"- onPicked: id => veyra.exportHevc = (id === "hevc")- }- }- VRow {- label: "分辨率"- hint: "跟随所选预设,或指定输出尺寸"- hintBelow: true- VSeg {- options: [- { id: "-1", label: "预设" },- { id: "0", label: "源" },- { id: "1", label: "2K" },- { id: "2", label: "4K" },- { id: "4", label: "5K" },- { id: "5", label: "6K" },- { id: "6", label: "7K" },- { id: "3", label: "8K" }- ]- current: String(veyra.exportSrTargetIndex)- onPicked: id => veyra.exportSrTargetIndex = parseInt(id)- }- }- VRow {- label: "码率"- value: veyra.exportBitrateMbps > 0 ? veyra.exportBitrateMbps + " Mbps" : "恒定质量"- RowLayout {- spacing: 6- VSlider {- implicitWidth: 90- from: 0- to: 200- value: Math.min(200, veyra.exportBitrateMbps)- onMoved: veyra.exportBitrateMbps = Math.round(value)- }- // Any value 0–2000 Mbps can be typed (0 = 恒定质量).- DialogHost.VTextField {- id: bitrateField- objectName: "export-bitrate-field"- implicitWidth: 56- text: String(veyra.exportBitrateMbps)- onEdited: value => {- const v = Math.round(Number(value))- if (isFinite(v)) veyra.exportBitrateMbps = Math.max(0, Math.min(2000, v))- bitrateField.text = String(veyra.exportBitrateMbps)+ ListView {+ id: queueList+ objectName: "export-queue-list"+ anchors { top: queueHead.bottom; topMargin: 8; left: parent.left; right: parent.right; bottom: parent.bottom; margins: 8 }+ clip: true+ spacing: 5+ model: veyra.exportQueueModel+ ScrollBar.vertical: ExportScrollBar {}+ delegate: Rectangle {+ id: row+ required property int index+ required property double itemId+ required property string name+ required property string input+ required property string output+ required property string state+ required property string note+ required property real progress+ required property real duration+ required property bool current+ required property bool locked+ required property bool inspecting+ objectName: "export-queue-row-" + index+ width: queueList.width; height: 72; radius: 9+ color: current ? Theme.card3 : rowHover.hovered ? Theme.card2 : "transparent"+ border.color: current ? Theme.accent : "transparent"+ HoverHandler { id: rowHover }+ TapHandler { onTapped: root.preview(row.itemId) }+ ToolTip.visible: rowHover.hovered && note.length > 0+ ToolTip.text: note + (output.length ? "\n" + output : "")+ RowLayout {+ anchors.fill: parent; anchors.margins: 6; spacing: 5+ Text {+ text: "≡"; color: row.locked ? Theme.t3 : Theme.t2+ Layout.preferredWidth: 18; Layout.fillHeight: true+ verticalAlignment: Text.AlignVCenter; font.pixelSize: 18+ MouseArea {+ objectName: "export-drag-" + row.index+ anchors.fill: parent; enabled: !row.locked; preventStealing: true; cursorShape: Qt.SizeVerCursor+ onPressed: mouse => { root.draggedId = row.itemId; root.dropIndex = row.index }+ onPositionChanged: mouse => {+ if (!pressed) return+ const point = mapToItem(queueList, mouse.x, mouse.y)+ root.dragY = point.y+ const target = queueList.indexAt(1, Math.max(0, Math.min(queueList.contentHeight - 1, point.y + queueList.contentY)))+ if (target >= 0) root.dropIndex = target+ }+ onReleased: {+ if (root.dropIndex >= 0) veyra.exportQueueModel.moveItem(root.draggedId, root.dropIndex)+ root.draggedId = 0; root.dropIndex = -1}+ onCanceled: { root.draggedId = 0; root.dropIndex = -1 }}}- }- VRow {- label: "策略"- VSeg {- options: [{ id: "0", label: "CBR" }, { id: "1", label: "VBR" }, { id: "2", label: "CQ" }]- current: String(veyra.exportRateControl)- onPicked: id => veyra.exportRateControl = parseInt(id)+ Image { source: veyra.fileThumbnailId(row.input, 0); asynchronous: true; fillMode: Image.PreserveAspectFit; Layout.preferredWidth: 44; Layout.preferredHeight: 42 }+ ColumnLayout {+ Layout.fillWidth: true; spacing: 3+ Text { Layout.fillWidth: true; text: row.name; color: Theme.t1; elide: Text.ElideMiddle; font.family: Theme.fontUi; font.pixelSize: 12 }+ Text { Layout.fillWidth: true; text: root.stateText(row.state, row.progress, row.inspecting); color: row.state === "failed" ? Theme.err : Theme.t3; elide: Text.ElideRight; font.family: Theme.fontUi; font.pixelSize: 10 }+ Text { Layout.fillWidth: true; text: row.duration > 0 ? veyra.formatTime(row.duration) : ""; color: Theme.t3; font.pixelSize: 10 }}- }- }-- VGroup {- visible: root.exportKind === "video"- VRow {- label: "增强预设"- hint: "节点预设待执行器接入"- hintBelow: true- VSelect {- value: veyra.exportPresetName- options: veyra.presetChoices- onPicked: id => veyra.selectExportPreset(parseInt(id))+ VButton {+ visible: row.state === "failed"+ ghost: true; text: "↻"; onClicked: veyra.exportQueueModel.retryItem(row.itemId)}- }- // The export copies the audio track that is playing, untouched.- VRow {- label: "音轨"- visible: veyra.hasSource && !veyra.isCapture- hint: veyra.audioTracks.length > 0 ? "原样复制,不重新编码;与播放时选的音轨相同" : (veyra.hasSource ? "这个文件没有音轨" : "")- hintBelow: true- VSelect {- objectName: "export-audio-track"- implicitWidth: 170- visible: veyra.audioTracks.length > 0- readonly property var tracks: veyra.audioTracks.map(t => ({ id: String(t.index), label: t.label }))- options: tracks- value: (tracks.find(t => Number(t.id) === veyra.selectedAudioTrack) || tracks[0] || { label: "默认" }).label- onPicked: id => veyra.selectedAudioTrack = Number(id)+ VButton {+ objectName: "export-remove-" + row.index+ ghost: true; text: "×"+ enabled: !row.locked+ onClicked: veyra.exportQueueModel.removeItem(row.itemId)}}- VRow {- label: "预计大小"- hint: veyra.exportSizeEstimate- visible: veyra.exportSizeEstimate.length > 0- }+ Rectangle { visible: root.draggedId > 0 && root.dropIndex === row.index; height: 2; width: parent.width; color: Theme.accent }}-- // What the export will run with. Frozen when it starts.- Rectangle {- visible: root.exportKind === "video"- Layout.fillWidth: true- implicitHeight: pinfo.implicitHeight + 16- radius: 9- color: Qt.rgba(1, 1, 1, 0.03)- ColumnLayout {- id: pinfo- anchors.fill: parent- anchors.margins: 8- spacing: 3- Text {- text: (veyra.exportHevc ? "HEVC" : "H.264") + " · "- + (["CBR", "VBR", "CQ"][veyra.exportRateControl]) + " · "- + (veyra.exportBitrateMbps > 0 ? veyra.exportBitrateMbps + " Mbps" : "自动质量")- color: Theme.t2- font.family: Theme.fontMono- font.pixelSize: Theme.fsSmall- }- Text {- Layout.fillWidth: true- text: "编码与码率在开始导出时固定;导出期间改设置不会影响正在进行的任务。"- color: Theme.t3- font.family: Theme.fontUi- font.pixelSize: 11- wrapMode: Text.WordWrap- }- }+ Column {+ anchors.centerIn: parent+ width: Math.max(1, parent.width - 24)+ visible: veyra.exportQueueModel.count === 0+ spacing: 8+ Text { width: parent.width; text: root.compact ? "添加或拖入多个视频" : "添加或拖入多个视频\n添加后不会立即导出"; horizontalAlignment: Text.AlignHCenter; color: Theme.t3; wrapMode: Text.Wrap; font.family: Theme.fontUi; font.pixelSize: 12 }+ VButton { anchors.horizontalCenter: parent.horizontalCenter; visible: veyra.hasSource && !veyra.isCapture && queueList.height > 80; text: "添加当前文件"; onClicked: veyra.addCurrentExportFile() }}-- // pages-b.js 保存到: a field with the path and a folder icon.- VRow {- visible: root.exportKind === "video"- label: "保存到"- Rectangle {- objectName: "export-target"- implicitWidth: 200- implicitHeight: Theme.ctlHeight- radius: Theme.rCtl- color: targetHover.hovered ? Theme.card3 : Theme.card2- border.width: 1- border.color: Theme.stroke2- RowLayout {- anchors.fill: parent- anchors.leftMargin: 10- anchors.rightMargin: 8- spacing: 6- Text {- Layout.fillWidth: true- text: veyra.exportTarget.length > 0 ? veyra.exportTarget : "选择输出位置…"- color: veyra.exportTarget.length > 0 ? Theme.t1 : Theme.t3- font.family: Theme.fontUi- font.pixelSize: 12- elide: Text.ElideMiddle- }- VIcon { name: "folder"; size: 14; color: Theme.t3 }- }- HoverHandler { id: targetHover; cursorShape: Qt.PointingHandCursor }- TapHandler { onTapped: veyra.chooseExportPath() }- }+ }+ Timer {+ interval: 60; repeat: true; running: root.draggedId > 0+ onTriggered: {+ const delta = root.dragY < 25 ? -16 : root.dragY > queueList.height - 25 ? 16 : 0+ queueList.contentY = Math.max(0, Math.min(Math.max(0, queueList.contentHeight - queueList.height), queueList.contentY + delta))}-- Item { Layout.fillHeight: true }-- // --- progress and the action ---------------------------------+ }+ DropArea {+ anchors.fill: parent+ onEntered: drag => { drag.accepted = drag.hasUrls }+ onDropped: drop => { if (drop.hasUrls) { veyra.addExportFiles(drop.urls); drop.acceptProposedAction() } }+ }+ }+ Rectangle {+ id: rightCol+ objectName: "export-settings-card"+ x: root.geometry.settings.x; y: root.geometry.settings.y+ width: root.geometry.settings.width; height: root.geometry.settings.height+ visible: !root.compact || root.compactTab === 2+ radius: Theme.rCard; color: Theme.card; border.color: Theme.stroke+ Basic.ScrollView {+ id: settingsScroll+ objectName: "export-settings-scroll"+ anchors.fill: parent; anchors.margins: 12+ contentWidth: availableWidth+ clip: true+ ScrollBar.vertical: ExportScrollBar {}+ ScrollBar.horizontal.policy: ScrollBar.AlwaysOffColumnLayout {- Layout.fillWidth: true- spacing: 8-- // pages-b.js .go: "预计 … · 约 …" over the progress bar.- Text {- objectName: "export-estimate"- Layout.fillWidth: true- visible: root.exportKind === "video" && text.length > 0- // Only real figures: a remaining time while exporting, a size when a- // bitrate fixes it (constant quality has no size until it runs).- readonly property bool sized: veyra.exportBitrateMbps > 0 && veyra.exportSizeEstimate.length > 0- text: veyra.exportRunning && veyra.exportEtaSeconds > 0- ? "预计还需 " + veyra.formatTime(veyra.exportEtaSeconds) + (sized ? " · " + veyra.exportSizeEstimate : "")- : sized ? "预计大小 " + veyra.exportSizeEstimate + " · 耗时开始后估算" : ""- color: Theme.t3- font.family: Theme.fontUi- font.pixelSize: 12- elide: Text.ElideRight- }- RowLayout {- Layout.fillWidth: true- Text {- Layout.fillWidth: true- text: veyra.exportStatus- color: Theme.t2- font.family: Theme.fontUi- font.pixelSize: 12- }- Text {- text: veyra.exportRunning ? (veyra.exportProgress * 100).toFixed(1) + "%" : ""- color: Theme.t1- font.family: Theme.fontMono- font.pixelSize: 11+ width: settingsScroll.availableWidth+ spacing: 10+ VH2 { text: "输出设置"; font.pixelSize: 14 }+ VRow { label: "类型"; VSeg { options: [{id: "video", label: "视频"}, {id: "image", label: "图片"}]; current: root.exportKind; onPicked: id => root.exportKind = id } }+ VGroup {+ visible: root.exportKind === "video"+ VRow { label: "封装"; VSeg { objectName: "export-container"; options: [{id: "0", label: "MP4"}, {id: "1", label: "MKV"}]; current: String(veyra.exportContainer); onPicked: id => veyra.exportContainer = Number(id) } }+ VRow { label: "视频编码"; VSeg { options: [{id: "0", label: "H.264"}, {id: "1", label: "HEVC"}]; current: veyra.exportHevc ? "1" : "0"; onPicked: id => veyra.exportHevc = id === "1" } }+ VRow {+ label: "分辨率"+ Choice {+ objectName: "export-resolution"+ options: [{id: "-1", label: "跟随增强预设"}, {id: "0", label: "源尺寸"}, {id: "1", label: "2K"}, {id: "2", label: "4K"}, {id: "4", label: "5K"}, {id: "5", label: "6K"}, {id: "6", label: "7K"}, {id: "3", label: "8K"}]+ selected: String(veyra.exportSrTargetIndex)+ onPicked: id => veyra.exportSrTargetIndex = Number(id)+ }}- Text {- visible: veyra.exportRunning && veyra.exportEtaSeconds > 0- text: "剩余约 " + veyra.formatTime(veyra.exportEtaSeconds)- color: Theme.t3- font.family: Theme.fontMono- font.pixelSize: 11+ VRow { label: "质量策略"; VSeg { options: [{id: "0", label: "CBR"}, {id: "1", label: "VBR"}, {id: "2", label: "CQ"}]; current: String(veyra.exportRateControl); onPicked: id => veyra.exportRateControl = Number(id) } }+ VRow {+ visible: veyra.exportRateControl !== 2+ label: "码率 Mbps"+ DialogHost.VTextField { objectName: "export-bitrate-field"; implicitWidth: 100; text: String(veyra.exportBitrateMbps); onEdited: value => { const n = Number(value); if (isFinite(n)) veyra.exportBitrateMbps = Math.max(1, Math.min(2000, Math.round(n))) } }}- }- Rectangle {- Layout.fillWidth: true- implicitHeight: 8- radius: 9- color: Qt.rgba(1, 1, 1, 0.08)- Rectangle {- height: parent.height- radius: 9- color: Theme.accent- width: parent.width * Math.max(0, Math.min(1, veyra.exportProgress))- Behavior on width { NumberAnimation { duration: Theme.d(300) } }+ Note { text: veyra.exportRateControl === 2 ? "CQ 使用恒定质量;文件大小随画面复杂度变化。" : "目标码率影响画质与文件大小。" }+ VRow { label: "增强预设"; Choice { options: veyra.presetChoices; selected: String((veyra.presetChoices.find(o => o.label === veyra.exportPresetName) || {id: "-1"}).id); onPicked: id => veyra.selectExportPreset(Number(id)) } }+ }+ VGroup {+ visible: root.exportKind === "video"+ Note { text: veyra.exportQueueModel.selectedId ? "所选文件的音轨与内嵌字幕" : "默认保留全部轨道;点击左侧文件可单独选择。" }+ VRow {+ label: "音轨"+ enabled: veyra.exportSelectionEditable+ Choice { options: [{id: "1", label: "保留全部"}, {id: "2", label: "选择轨道"}, {id: "3", label: "不保留"}]; selected: String(veyra.exportAudioPolicy); onPicked: id => veyra.setExportTrackPolicy(true, Number(id)) }}- }- // Counts come from the job's own snapshot, not a parallel counter.- Text {- visible: veyra.exportRunning- text: "已编码 " + veyra.exportEncoded + " 帧 · 生成 " + veyra.exportGenerated + " 帧"- color: Theme.t3- font.family: Theme.fontMono- font.pixelSize: 11- }-- RowLayout {- Layout.fillWidth: true- spacing: 8- VButton {- objectName: "export-start"- Layout.fillWidth: true- implicitHeight: 42- primary: !veyra.exportRunning- enabled: root.exportKind === "video"- iconName: veyra.exportRunning ? (veyra.exportPaused ? "upload" : "pause") : "upload"- text: veyra.exportRunning ? (veyra.exportPaused ? "继续导出" : "暂停导出") : "开始导出"- onClicked: veyra.exportRunning ? veyra.pauseExport(!veyra.exportPaused)- : veyra.startExport()+ VRow {+ label: "内嵌字幕"+ enabled: veyra.exportSelectionEditable+ Choice { options: [{id: "1", label: "保留全部"}, {id: "2", label: "选择轨道"}, {id: "3", label: "不保留"}]; selected: String(veyra.exportSubtitlePolicy); onPicked: id => veyra.setExportTrackPolicy(false, Number(id)) }}- VButton {- visible: veyra.exportRunning- text: "取消"- onClicked: veyra.cancelExport()+ Repeater {+ model: veyra.exportTracks+ delegate: ColumnLayout {+ required property var modelData+ Layout.fillWidth: true; spacing: 1+ Basic.CheckBox {+ id: trackCheck+ Layout.fillWidth: true+ implicitHeight: 28+ enabled: veyra.exportSelectionEditable+ checked: modelData.selected+ text: modelData.label+ indicator: Rectangle {+ x: trackCheck.leftPadding; y: (trackCheck.height - height) / 2+ implicitWidth: 17; implicitHeight: 17; radius: 4+ color: trackCheck.checked ? (trackCheck.enabled ? Theme.accent : Theme.t3) : Theme.card2+ border.color: trackCheck.checked ? color : Theme.stroke2+ Text { anchors.centerIn: parent; text: "✓"; visible: trackCheck.checked; color: Theme.card; font.pixelSize: 12 }+ }+ contentItem: Text { text: parent.text; leftPadding: parent.indicator.width + 8; color: Theme.t2; font.pixelSize: 11; elide: Text.ElideRight; verticalAlignment: Text.AlignVCenter }+ onClicked: veyra.toggleExportTrack(modelData.audio, modelData.index, checked)+ }+ Note { text: modelData.action; color: modelData.compatible ? Theme.t3 : Theme.err }+ }}- }+ Note { text: "音轨直接复制,不改变声道数。MKV 可保留 ASS 样式和字体;“保留全部”时当前封装装不下的轨道会跳过并提示,手动选中的轨道装不下会报错。" }+ }+ VGroup {+ visible: root.exportKind === "image"+ VButton { Layout.fillWidth: true; text: "导出当前画面"; enabled: veyra.hasSource && !veyra.imageBatchActive; onClicked: veyra.saveFrameDialog() }+ VButton { Layout.fillWidth: true; text: "批量处理图片…"; enabled: !veyra.imageBatchActive; onClicked: veyra.exportImagesDialog() }+ Note { text: veyra.imageBatchStatus }+ VButton { visible: veyra.imageBatchActive; text: "取消图片批次"; onClicked: veyra.cancelImageBatch() }+ }+ Note { visible: root.exportKind === "video"; text: "点击开始时冻结本批设置;导出期间可以继续预览其他文件。" }+ VButton { objectName: "export-target"; Layout.fillWidth: true; iconName: "folder"; text: "选择保存目录…"; onClicked: veyra.chooseExportPath() }+ Note { text: veyra.exportTarget; wrapMode: Text.WrapAnywhere }+ VRow { label: "完成提示音"; VSwitch { objectName: "export-sound"; checked: veyra.exportCompletionSound; onToggled: veyra.exportCompletionSound = checked } }}}}+ Rectangle {+ objectName: "export-footer"+ x: root.geometry.footer.x; y: root.geometry.footer.y+ width: root.geometry.footer.width; height: root.geometry.footer.height+ radius: Theme.rCard; color: Theme.card; border.color: Theme.stroke+ ColumnLayout {+ anchors.fill: parent; anchors.margins: root.compact ? 6 : 10; spacing: 5+ Text { objectName: "export-status"; Layout.fillWidth: true; visible: !root.compact; text: veyra.exportStatus; color: Theme.t2; font.family: Theme.fontUi; font.pixelSize: 11; elide: Text.ElideRight; ToolTip.text: text; ToolTip.visible: statusHover.hovered; HoverHandler { id: statusHover } }+ Basic.ProgressBar {+ id: exportProgressBar+ objectName: "export-progress"; Layout.fillWidth: true; Layout.preferredHeight: 5; from: 0; to: 1; value: veyra.exportProgress+ background: Rectangle { implicitHeight: 5; radius: 3; color: Theme.card3 }+ contentItem: Item { Rectangle { width: exportProgressBar.visualPosition * parent.width; height: parent.height; radius: 3; color: Theme.accent } }+ }+ RowLayout {+ Layout.fillWidth: true; spacing: 6+ Text { visible: root.compact; Layout.fillWidth: true; text: veyra.exportStatus; color: Theme.t2; elide: Text.ElideRight; font.pixelSize: 11 }+ VButton { objectName: "export-start"; Layout.fillWidth: !root.compact; primary: !veyra.exportRunning; text: veyra.exportRunning ? (veyra.exportPaused ? "继续导出" : "暂停导出") : "开始导出 " + veyra.exportReadyCount + " 项"; enabled: root.exportKind === "video" && (veyra.exportRunning || veyra.exportReadyCount > 0); onClicked: veyra.exportRunning ? veyra.pauseExport(!veyra.exportPaused) : veyra.startExport() }+ VButton { objectName: "export-cancel"; visible: veyra.exportRunning; text: "取消"; onClicked: veyra.cancelExport() }+ }+ Note { visible: !root.compact; text: veyra.exportRunning ? "已编码 " + veyra.exportEncoded + " 帧 · 等待 " + veyra.exportQueueCount + " 项" : "取消后可重新开始;已完成文件会跳过。" }+ }+ }// --- middle: picture, then the trim card ------------------------------Rectangle {id: vwrap- anchors.left: parent.left- anchors.leftMargin: 14 + 250 + 10- anchors.right: rightCol.left- anchors.rightMargin: 10- anchors.top: head.bottom- anchors.topMargin: 10- anchors.bottom: trimCard.top- anchors.bottomMargin: 10+ objectName: "export-preview-card"+ x: root.geometry.preview.x; y: root.geometry.preview.y+ width: root.geometry.preview.width; height: root.geometry.preview.height+ visible: !root.compact || root.compactTab === 1radius: Theme.rCardcolor: Theme.videoBlackborder.width: 1@@ -610,18 +401,17 @@ VPage {Rectangle {id: trimCard- anchors.left: vwrap.left- anchors.right: vwrap.right- anchors.bottom: parent.bottom- anchors.bottomMargin: 14- height: 92+ objectName: "export-trim-card"+ x: root.geometry.trim.x; y: root.geometry.trim.y+ width: root.geometry.trim.width; height: root.geometry.trim.height+ visible: !root.compact || root.compactTab === 1radius: Theme.rCardcolor: Theme.cardborder.width: 1border.color: Theme.stroke// 入点 / 出点 (user request 2026-09-29): play or scrub to a spot, then// mark it. One timeline shows the playhead, the kept range and both marks.- readonly property bool editable: veyra.hasSource && !veyra.exportRunning && veyra.duration > 0+ readonly property bool editable: veyra.hasSource && veyra.exportSelectionEditable && veyra.duration > 0readonly property real inAt: veyra.exportTrimStartreadonly property real outAt: veyra.exportTrimEnd > 0 ? veyra.exportTrimEnd : veyra.durationfunction frac(t) { return veyra.duration > 0 ? Math.max(0, Math.min(1, t / veyra.duration)) : 0 }@@ -641,13 +431,13 @@ VPage {Shortcut { sequence: "O"; enabled: trimCard.visible && trimCard.editable && root.visible; onActivated: trimCard.markOut() }ColumnLayout {anchors.fill: parent- anchors.margins: 12- spacing: 8+ anchors.margins: 8+ spacing: 4Item {id: timelineobjectName: "export-timeline"Layout.fillWidth: true- Layout.preferredHeight: 30+ Layout.preferredHeight: root.compact ? 18 : 30property bool scrubbing: falseproperty real scrubFrac: 0readonly property real head: scrubbing ? scrubFrac : trimCard.frac(veyra.position)@@ -744,12 +534,12 @@ VPage {text: veyra.positionTextcolor: Theme.t2; font.family: Theme.fontMono; font.pixelSize: Theme.fsSmall}- Item { Layout.preferredWidth: 6 }- VButton { objectName: "export-mark-in"; text: "设为入点 I"; enabled: trimCard.editable; onClicked: trimCard.markIn() }- VButton { objectName: "export-mark-out"; text: "设为出点 O"; enabled: trimCard.editable; onClicked: trimCard.markOut() }++ VButton { objectName: "export-mark-in"; text: "入点 I"; enabled: trimCard.editable; onClicked: trimCard.markIn() }+ VButton { objectName: "export-mark-out"; text: "出点 O"; enabled: trimCard.editable; onClicked: trimCard.markOut() }VSeg {objectName: "export-compare"- options: [{ id: "0", label: "增强" }, { id: "2", label: "分屏对比" }]+ options: [{ id: "0", label: "增强" }, { id: "2", label: "对比" }]current: veyra.compareMode === 2 ? "2" : "0"onPicked: id => veyra.compareMode = Number(id)}@@ -760,11 +550,13 @@ VPage {onClicked: { veyra.exportTrimStart = 0; veyra.exportTrimEnd = 0 }}Item { Layout.fillWidth: true }- Text {- text: "导出 " + veyra.formatTime(trimCard.inAt) + " — " + veyra.formatTime(trimCard.outAt)- + "(" + veyra.formatTime(Math.max(0, trimCard.outAt - trimCard.inAt)) + ")"- color: Theme.t1; font.family: Theme.fontMono; font.pixelSize: Theme.fsSmall- }+ }+ Text {+ Layout.fillWidth: true+ visible: !root.compact+ text: "导出 " + veyra.formatTime(trimCard.inAt) + " — " + veyra.formatTime(trimCard.outAt)+ color: Theme.t2; font.family: Theme.fontMono; font.pixelSize: 11+ elide: Text.ElideRight}}}diff --git a/qml/Veyra/Main.qml b/qml/Veyra/Main.qmlindex 0d56cc38..134626b8 100644--- a/qml/Veyra/Main.qml+++ b/qml/Veyra/Main.qml@@ -15,6 +15,7 @@import QtQuickimport QtQuick.Controlsimport QtQuick.Layouts+import "ExportLayout.js" as ExportLayoutWindow {id: root@@ -188,11 +189,7 @@ Window {// it resizes it) minus its 40px bar.return { x: 14, y: 14, width: Math.max(1, width - 28), height: root.nodeVideoHeight - 40 }case "exp":- // .exp grid: 250px 1fr 330px; the video is column 2 row 2.- return { x: 14 + 250 + 10,- y: 14 + 32 + 10,- width: Math.max(1, width - 250 - 330 - 14 * 2 - 20),- height: Math.max(1, height - 14 * 2 - 32 - 10 - 120 - 10) }+ return ExportLayout.calculate(width, height, exportPage.compactTab).videodefault:return { x: 0, y: 0, width: 0, height: 0 }}@@ -239,7 +236,7 @@ Window {root.page = "pro"}}- ExportPage { pageId: "exp"; onRequestPage: p => root.goPage(p) }+ ExportPage { id: exportPage; pageId: "exp"; onRequestPage: p => root.goPage(p) }SettingsPage { pageId: "set"; onRequestPage: p => root.goPage(p) }}diff --git a/scripts/acceptance/export-page-build.py b/scripts/acceptance/export-page-build.pynew file mode 100644index 00000000..fbb4471f--- /dev/null+++ b/scripts/acceptance/export-page-build.py@@ -0,0 +1,48 @@+"""Task-specific build, with read-only dependency reuse and bounded subprocesses."""+import os+from pathlib import Path+import subprocess+import sys++ROOT = Path(__file__).resolve().parents[2]+BASE = Path('E:/项目/Veyra')+BUILD = BASE / 'build/export-page-20261002'+TMP = BASE / 'tmp/export-page-20261002/build'+LOGS = BASE / 'logs/export-page-20261002'+subprocess.run([sys.executable, '-B', str(ROOT / 'scripts/acceptance/export-page-control.py')], check=True)+for path in (BUILD, TMP, LOGS):+ path.mkdir(parents=True, exist_ok=True)+cache = BASE / 'build/field-issues-20260930-clean/CMakeCache.txt'+settings = []+for line in cache.read_text(encoding='utf-8').splitlines():+ if ':' not in line or '=' not in line:+ continue+ keytype, value = line.split('=', 1)+ key, kind = keytype.split(':', 1)+ if kind in ('INTERNAL', 'STATIC'):+ continue+ if (key.startswith('VEYRA_') and (key.endswith('_ROOT') or key.endswith('_DIR'))) or key in ('CMAKE_PREFIX_PATH', 'CMAKE_MAKE_PROGRAM', 'PROTOC', 'PKG_CONFIG_EXECUTABLE'):+ settings.append(f'set({key} [[{value}]] CACHE {kind} "Read-only dependency location" FORCE)')+settings += ['set(VEYRA_BUILD_QML_UI ON CACHE BOOL "QML" FORCE)',+ 'set(VEYRA_ENABLE_REMOTEPLAY ON CACHE BOOL "Preserve product configuration" FORCE)',+ 'set(VEYRA_ENABLE_EXPERIMENTAL_DLSSNR ON CACHE BOOL "Existing runtime API" FORCE)']+(TMP / 'dependencies.cmake').write_text('\n'.join(settings), encoding='utf-8')+targets = sys.argv[2:] or ['veyra_qml_ui', 'veyra_qml_quick_tests', 'veyra_qml_data_tests', 'veyra_qml_easing_tests', 'veyra_export_workflow_tests']+if any(not all(c.isalnum() or c == '_' for c in t) for t in targets):+ raise SystemExit('Invalid target')+cmd = TMP / 'build.cmd'+cmd.write_text('@echo off\nchcp 65001 >nul\ncall "C:\\Program Files (x86)\\Microsoft Visual Studio\\2022\\BuildTools\\VC\\Auxiliary\\Build\\vcvars64.bat" >nul 2>&1\nif errorlevel 1 exit /b 4\n"%EXPORT_CMAKE%" --preset x64-release -S "%EXPORT_ROOT%" -B "%EXPORT_BUILD%" -C "%EXPORT_TMP%\\dependencies.cmake"\nif errorlevel 1 exit /b 5\n"%EXPORT_CMAKE%" --build "%EXPORT_BUILD%" --parallel 4 --target ' + ' '.join(targets) + '\nexit /b %errorlevel%\n', encoding='ascii')+env = os.environ.copy()+env.update(VSLANG='1033', EXPORT_ROOT=str(ROOT), EXPORT_BUILD=str(BUILD), EXPORT_TMP=str(TMP), TEMP=str(TMP), TMP=str(TMP), EXPORT_CMAKE='C:/Program Files (x86)/Microsoft Visual Studio/2022/BuildTools/Common7/IDE/CommonExtensions/Microsoft/CMake/CMake/bin/cmake.exe')+log = LOGS / (sys.argv[1] if len(sys.argv) > 1 else 'build-001.log')+if log.exists():+ raise SystemExit('Refusing to overwrite build evidence')+with log.open('w', encoding='utf-8') as out:+ try:+ result = subprocess.run(['cmd.exe', '/d', '/c', str(cmd)], cwd=ROOT, env=env, stdout=out, stderr=subprocess.STDOUT, timeout=900).returncode+ except subprocess.TimeoutExpired:+ result = 124+print('BUILD', result, log)+print('\n'.join(log.read_text(encoding='utf-8', errors='replace').splitlines()[-32:]))+subprocess.run([sys.executable, '-B', str(ROOT / 'scripts/acceptance/export-page-control.py')], check=True)+raise SystemExit(result)diff --git a/scripts/acceptance/export-page-control.py b/scripts/acceptance/export-page-control.pynew file mode 100644index 00000000..704dd9c4--- /dev/null+++ b/scripts/acceptance/export-page-control.py@@ -0,0 +1,69 @@+"""Scope protection for the isolated export task. Never refresh an existing baseline."""+import hashlib+import json+from pathlib import Path+import subprocess+import sys++ROOT = Path(__file__).resolve().parents[2]+BASE = Path('E:/项目/Veyra/archives/export-page-20261002-start')+BASELINE = BASE / 'scope-baseline.json'+BRANCH = 'codex/export-page-20261002'+ALLOW = {+ 'AGENTS.md', 'CMakeLists.txt', 'docs/WORKLOG.md',+ 'docs/EXPORT_PAGE_OPTIMIZATION_PLAN_2026-10-02.md',+ 'docs/EXPORT_PAGE_EXECUTION_2026-10-02.md',+ 'qml/Veyra/ExportPage.qml', 'qml/Veyra/Main.qml', 'qml/Veyra/ExportLayout.js',+ 'include/veyra/engine/ExportOptions.h', 'include/veyra/engine/EngineController.h',+ 'include/veyra/engine/ExportJobManager.h', 'src/engine/ExportJobManager.cpp',+ 'src/engine/VideoExportJob.cpp', 'include/veyra/engine/ExportStreams.h', 'src/engine/ExportStreams.cpp',+ 'include/veyra/engine/ExportQueue.h', 'src/engine/ExportQueue.cpp',+ 'include/veyra/ui/QmlExportQueueModel.h', 'src/ui/QmlExportQueueModel.cpp',+ 'include/veyra/ui/QmlPlayerBridge.h', 'src/ui/QmlPlayerBridge.cpp',+ 'tests/integration/ExportWorkflowTests.cpp', 'tests/unit/ExportQueueTests.cpp',+ 'tests/qml/QuickSmokeTests.cpp', 'tests/qml/quick/tst_export.qml',+ 'scripts/acceptance/export-page-build.py', 'scripts/acceptance/export-page-tests.py',+ 'scripts/acceptance/export-page-ui.qml',+}++def git(*args):+ return subprocess.check_output(['git', '--no-optional-locks', *args], cwd=ROOT).decode('utf-8').strip()++def files():+ raw = subprocess.check_output(['git', 'ls-files', '-z', '--cached', '--others', '--exclude-standard'], cwd=ROOT)+ return sorted(set(raw.decode('utf-8').rstrip('\0').split('\0')))++def sha(path):+ return hashlib.sha256(path.read_bytes()).hexdigest() if path.is_file() else None++if git('branch', '--show-current') != BRANCH:+ raise SystemExit('FAIL: wrong branch')+if ROOT != Path('E:/项目/Veyra/worktrees/export-page-20261002'):+ raise SystemExit('FAIL: wrong workspace')+if len(sys.argv) > 1 and sys.argv[1] == 'init':+ if BASELINE.exists():+ raise SystemExit('Refusing to replace existing scope baseline')+ BASE.mkdir(parents=True, exist_ok=True)+ paths = files()+ baseline = dict(head=git('rev-parse', 'HEAD'), branch=BRANCH,+ allow=sorted(ALLOW), files={f: sha(ROOT / f) for f in paths})+ BASELINE.write_text(json.dumps(baseline, ensure_ascii=False, indent=2), encoding='utf-8')+ (BASE / 'working-tree.patch').write_bytes(subprocess.check_output(['git', 'diff', '--binary', 'HEAD'], cwd=ROOT))+ for f in paths:+ if f in ALLOW and (ROOT / f).is_file():+ out = BASE / 'source' / f+ out.parent.mkdir(parents=True, exist_ok=True)+ out.write_bytes((ROOT / f).read_bytes())+ print('BASELINE', sha(BASELINE), 'files', len(paths))+else:+ b = json.loads(BASELINE.read_text(encoding='utf-8'))+ errors = []+ if b['head'] != git('rev-parse', 'HEAD'):+ errors.append('HEAD changed')+ if b['allow'] != sorted(ALLOW):+ errors.append('Allow list changed')+ for f in set(files()) | set(b['files']):+ if f not in ALLOW and sha(ROOT / f) != b['files'].get(f):+ errors.append(f)+ print(json.dumps(dict(status='FAIL' if errors else 'PASS', checked=len(b['files']), errors=errors), ensure_ascii=False))+ raise SystemExit(bool(errors))diff --git a/scripts/acceptance/export-page-tests.py b/scripts/acceptance/export-page-tests.pynew file mode 100644index 00000000..6a9735fb--- /dev/null+++ b/scripts/acceptance/export-page-tests.py@@ -0,0 +1,220 @@+"""Bounded product export tests. All generated files stay in the task's E: tree."""+import json+import os+from pathlib import Path+import shutil+import subprocess+import sys++ROOT = Path(__file__).resolve().parents[2]+BASE = Path('E:/项目/Veyra')+TEST = BASE / 'tests/export-page-20261002'+LOG = BASE / 'logs/export-page-20261002'+APP = TEST / 'engine-app'+MEDIA = TEST / 'media'+BUILD = BASE / 'build/export-page-20261002'+TMP = BASE / 'tmp/export-page-20261002/tests'+for path in (APP, MEDIA, TMP):+ path.mkdir(parents=True, exist_ok=True)+env = os.environ.copy()+env.update(TEMP=str(TMP), TMP=str(TMP))++def run(args, name, expected=0):+ target = LOG / (name + '.log')+ if target.exists():+ raise RuntimeError('Refusing to overwrite evidence: ' + str(target))+ startup = subprocess.STARTUPINFO()+ startup.dwFlags |= subprocess.STARTF_USESHOWWINDOW+ startup.wShowWindow = 0+ with target.open('wb') as out:+ code = subprocess.run([str(x) for x in args], cwd=APP, env=env,+ stdout=out, stderr=subprocess.STDOUT, timeout=290, startupinfo=startup).returncode+ print(name, code, target)+ if code != expected:+ print(target.read_text(encoding='utf-8', errors='replace')[-7000:])+ raise RuntimeError('Unexpected exit code')++def stage():+ # Dependency snapshot was audited by stage-ui-migration.ps1. Copy from our+ # own baseline, never into another agent's candidate or build directory.+ source = TEST / 'baseline-app'+ if not source.is_dir():+ source = BASE / 'test-packages/export-page-20261002'+ for dll in source.glob('*.dll'):+ shutil.copy2(dll, APP / dll.name)+ for folder in ('shaders', 'runtime'):+ if not (APP / folder).exists():+ shutil.copytree(source / folder, APP / folder)+ (APP / 'runtime_local').mkdir(exist_ok=True)+ (APP / 'logs').mkdir(exist_ok=True)+ shutil.copy2(BUILD / 'veyra_export_workflow_tests.exe', APP)++mode = sys.argv[1]+tag = sys.argv[2] if len(sys.argv) > 2 else '001'+subprocess.run([sys.executable, '-B', str(ROOT / 'scripts/acceptance/export-page-control.py')], check=True)+if mode == 'generate':+ subtitles = MEDIA / 'crossing.srt'+ subtitles.write_text('1\n00:00:00,200 --> 00:00:01,300\nCrosses the trim in point\n\n2\n00:00:01,500 --> 00:00:02,700\nSecond subtitle\n', encoding='utf-8')+ for container, codec in [('mkv', 'srt'), ('mp4', 'mov_text')]:+ run(['ffmpeg', '-v', 'warning', '-n', '-f', 'lavfi', '-i', 'testsrc2=size=320x180:rate=10:duration=3',+ '-f', 'lavfi', '-i', 'sine=frequency=440:sample_rate=48000:duration=3',+ '-f', 'lavfi', '-i', 'sine=frequency=880:sample_rate=48000:duration=3',+ '-i', subtitles, '-map', '0:v', '-map', '1:a', '-map', '2:a', '-map', '3:s', '-map', '3:s',+ '-c:v', 'libx264', '-threads', '2', '-pix_fmt', 'yuv420p', '-c:a', 'aac', '-c:s', codec,+ '-metadata:s:a:0', 'language=eng', '-metadata:s:a:0', 'title=English',+ '-metadata:s:a:1', 'language=jpn', '-metadata:s:a:1', 'title=Japanese',+ '-metadata:s:s:0', 'language=eng', '-metadata:s:s:1', 'language=zho',+ '-disposition:a:0', 'default', '-disposition:a:1', '0', '-disposition:s:1', 'forced',+ MEDIA / ('tracks.' + container)], 'fixture-' + container + '-' + tag)+elif mode == 'generate-extra':+ ass = MEDIA / 'styled.ass'+ ass.write_text('[Script Info]\nScriptType: v4.00+\nPlayResX: 320\nPlayResY: 180\n[V4+ Styles]\nFormat: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding\nStyle: Default,Arial,20,&H0000FFFF,&H000000FF,&H00000000,&H80000000,-1,0,0,0,100,100,0,0,1,2,1,2,10,10,10,1\n[Events]\nFormat: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text\nDialogue: 0,0:00:00.20,0:00:02.70,Default,,0,0,0,,Styled {\\i1}subtitle{\\i0}\n', encoding='utf-8')+ run(['ffmpeg', '-v', 'warning', '-n', '-i', MEDIA / 'tracks.mkv', '-i', ass,+ '-map', '0:v', '-map', '0:a', '-map', '1:s', '-c', 'copy', '-attach', 'C:/Windows/Fonts/arial.ttf',+ '-metadata:s:t', 'mimetype=application/x-truetype-font', '-metadata:s:t', 'filename=Arial.ttf', MEDIA / 'font-ass.mkv'], 'fixture-font-' + tag)+ run(['ffmpeg', '-v', 'warning', '-n', '-i', MEDIA / 'tracks.mkv', '-f', 'lavfi', '-i',+ 'aevalsrc=0.1*sin(2*PI*220*t)|0.1*sin(2*PI*330*t)|0.1*sin(2*PI*440*t)|0.1*sin(2*PI*60*t)|0.1*sin(2*PI*550*t)|0.1*sin(2*PI*660*t):s=48000:d=3:c=5.1',+ '-map', '0:v', '-map', '1:a', '-map', '0:a', '-map', '0:s', '-c', 'copy', '-c:a:0', 'flac',+ '-metadata:s:a:0', 'language=eng', '-metadata:s:a:0', 'title=Six discrete channels', MEDIA / 'six-channel.mkv'], 'fixture-six-' + tag)+ run(['ffmpeg', '-v', 'warning', '-n', '-i', MEDIA / 'tracks.mp4', '-map', '0:v', '-c', 'copy', MEDIA / 'silent.mp4'], 'fixture-silent-' + tag)+ sparse = MEDIA / 'sparse.srt'+ sparse.write_text('1\n00:00:00,200 --> 00:00:01,000\nOpening\n\n2\n00:00:29,000 --> 00:00:30,000\nA sparse subtitle\n', encoding='utf-8')+ run(['ffmpeg', '-v', 'warning', '-n', '-stream_loop', '9', '-i', MEDIA / 'tracks.mp4', '-i', sparse,+ '-map', '0:v', '-map', '0:a', '-map', '1:s', '-c', 'copy', '-c:s', 'srt', '-t', '30', MEDIA / 'sparse.mkv'], 'fixture-sparse-' + tag)+elif mode == 'regression':+ stage()+ for name in ('veyra_export_queue_tests.exe', 'veyra_qml_data_tests.exe', 'veyra_export_worker_failure_tests.exe'):+ shutil.copy2(BUILD / name, APP)+ run([APP / 'veyra_export_queue_tests.exe', TEST], 'queue-unit-' + tag)+ run([APP / 'veyra_qml_data_tests.exe', TEST / ('data-' + tag)], 'qml-data-' + tag)+ env['VEYRA_TEST_COLOR_CHAIN_DATA_ROOT'] = str(APP / 'runtime_local')+ run([APP / 'veyra_export_worker_failure_tests.exe', 'color-chain', MEDIA / 'tracks.mp4', TEST / ('color-' + tag)], 'color-chain-' + tag)+ qml_app = TEST / 'candidate-ui-001'+ shutil.copy2(BUILD / 'veyra_qml_easing_tests.exe', qml_app)+ env.update(QT_QPA_PLATFORM='offscreen', QT_QPA_FONTDIR='C:/Windows/Fonts')+ run([qml_app / 'veyra_qml_easing_tests.exe'], 'qml-easing-' + tag)+elif mode in ('qml', 'qml-full'):+ app = TEST / 'candidate-ui-001'+ if not app.is_dir():+ shutil.copytree(BASE / 'test-packages/export-page-20261002', app)+ for name in ('veyra_qml_quick_tests.exe', 'veyra_qml_ui.exe'):+ shutil.copy2(BUILD / name, app / name)+ shutil.copytree(ROOT / 'qml', app / 'qml', dirs_exist_ok=True)+ shutil.copytree(ROOT / 'tests/qml/quick', app / 'qml-tests', dirs_exist_ok=True)+ artifacts = TEST / ('qml-' + tag)+ artifacts.mkdir(exist_ok=True)+ env.update(QT_QPA_PLATFORM='offscreen', QT_QUICK_BACKEND='software', QT_QUICK_CONTROLS_STYLE='Basic',+ QT_FORCE_STDERR_LOGGING='1', QT_QPA_FONTDIR='C:/Windows/Fonts',+ QT_SCALE_FACTOR=tag.split('-')[0], VEYRA_EXPORT_TEST_ARTIFACTS=str(artifacts))+ run([app / 'veyra_qml_quick_tests.exe', '-input', app / ('qml-tests/tst_export.qml' if mode == 'qml' else 'qml-tests'),+ '-o', str(LOG / ('qml-' + tag + '-results.log')) + ',txt'], 'qml-' + tag)+ print((LOG / ('qml-' + tag + '-results.log')).read_text(encoding='utf-8', errors='replace')[-2000:])+ for name in ('export-1280.png', 'export-720-settings.png'):+ pixels = (artifacts / name).read_bytes()+ assert pixels.startswith(b'\x89PNG\r\n\x1a\n') and len(pixels) > 1000+elif mode == 'ui':+ app = Path(os.environ.get('VEYRA_EXPORT_UI_APP', str(TEST / 'candidate-ui-001')))+ if not app.is_dir():+ shutil.copytree(BASE / 'test-packages/export-page-20261002', app)+ shutil.copy2(BUILD / 'veyra_qml_ui.exe', app)+ shutil.copytree(ROOT / 'qml', app / 'qml', dirs_exist_ok=True)+ artifacts = TEST / ('production-ui-' + tag)+ artifacts.mkdir(exist_ok=False)+ output = artifacts / 'outputs'+ output.mkdir()+ (artifacts / 'images').mkdir()+ (artifacts / 'cancel-images').mkdir()+ (MEDIA / 'broken.mkv').write_text('Intentionally invalid local test fixture', encoding='utf-8')+ main = app / 'qml/Veyra/Main.qml'+ original = main.read_bytes()+ source = original.decode('utf-8')+ loader = '\nLoader { source: ' + json.dumps((ROOT / 'scripts/acceptance/export-page-ui.qml').as_uri()) + '; onLoaded: { item.outputDirectory = ' + json.dumps(str(output)) + '; item.evidenceDirectory = ' + json.dumps(str(artifacts)) + ' } }\n'+ try:+ at = source.rfind('}')+ main.write_text(source[:at] + loader + source[at:], encoding='utf-8')+ env.update(QT_FORCE_STDERR_LOGGING='1')+ run([app / 'veyra_qml_ui.exe', '--page', 'exp', '--size', '1280x720', '--reduced-motion',+ '--export-out', output, '--data-dir', artifacts / 'profile', '--exit-after', '125000'], 'production-ui-' + tag)+ finally:+ main.write_bytes(original)+ result = (LOG / ('production-ui-' + tag + '.log')).read_text(encoding='utf-8', errors='replace')+ assert 'EXPORT_UI_PASS' in result and 'EXPORT_UI_FAIL' not in result, result[-4000:]+ notices = [line for line in result.splitlines() if '[export-notify]' in line]+ assert len(notices) == 3 and sum('systemSoundQueued=true' in line for line in notices) == 2, notices+ assert any('soundEnabled=false systemSoundQueued=false' in line for line in notices)+ assert sum('kind=image-batch' in line for line in notices) == 1+ prefs = json.loads((artifacts / 'profile/qml-preferences.v1.json').read_text(encoding='utf-8'))+ assert prefs['exportCompletionSound'] is False+ assert (artifacts / 'production-export.png').is_file()+elif mode == 'queue':+ stage()+ folder = TEST / ('queue-' + tag)+ run([APP / 'veyra_export_workflow_tests.exe', mode, MEDIA / 'tracks.mp4', folder], mode + '-' + tag)+ outputs = sorted(folder.glob('*.mp4'))+ assert len(outputs) == 4, outputs+ for index, path in enumerate(outputs):+ raw = subprocess.check_output(['ffprobe', '-v', 'error', '-count_frames', '-show_streams', '-of', 'json', str(path)], env=env, timeout=30)+ (LOG / (mode + '-' + tag + '-probe-' + str(index) + '.json')).write_bytes(raw)+ streams = json.loads(raw)['streams']+ assert [s['codec_type'] for s in streams] == ['video', 'audio', 'audio', 'subtitle', 'subtitle']+ assert int(streams[0]['nb_read_frames']) == 30+ print('PASS actual queue outputs', len(outputs))+else:+ stage()+ container = 'mkv' if 'mkv' in mode else 'mp4'+ source = MEDIA / ('tracks.' + ('mp4' if 'convert' in mode and container == 'mkv' else 'mkv' if 'convert' in mode else container))+ if len(sys.argv) > 3:+ source = Path(sys.argv[3])+ output = TEST / (mode + '-' + tag + '.' + container)+ run([APP / 'veyra_export_workflow_tests.exe', mode, source, output], mode + '-' + tag)+ if mode == 'lifecycle-boundary':+ assert output.exists()+ raise SystemExit(0)+ if 'reject' in mode:+ assert not output.exists()+ raise SystemExit(0)+ raw = subprocess.check_output(['ffprobe', '-v', 'error', '-count_frames', '-show_streams', '-show_format', '-of', 'json', str(output)], env=env, timeout=30)+ (LOG / (mode + '-' + tag + '-probe.json')).write_bytes(raw)+ data = json.loads(raw)+ video = [s for s in data['streams'] if s['codec_type'] == 'video']+ audio = [s for s in data['streams'] if s['codec_type'] == 'audio']+ subs = [s for s in data['streams'] if s['codec_type'] == 'subtitle']+ assert len(video) == 1+ if mode == 'lifecycle':+ assert int(video[0]['nb_read_frames']) == 20+ else:+ source_data = json.loads(subprocess.check_output(['ffprobe', '-v', 'error', '-show_streams', '-of', 'json', str(source)], env=env, timeout=30))+ source_audio = [s for s in source_data['streams'] if s['codec_type'] == 'audio']+ source_subs = [s for s in source_data['streams'] if s['codec_type'] == 'subtitle']+ if 'none' in mode:+ source_audio = source_subs = []+ elif 'skip' in mode:+ # Bitmap subtitles the container/trim cannot carry are left out.+ source_subs = [s for s in source_subs if s.get('codec_name') != 'hdmv_pgs_subtitle']+ elif 'selected' in mode:+ source_audio = source_audio[1:2]+ source_subs = source_subs[1:2]+ assert len(audio) == len(source_audio) and len(subs) == len(source_subs), data+ for original, copied in zip(source_audio, audio):+ for key in ('codec_name', 'channels', 'channel_layout'):+ assert copied.get(key) == original.get(key), (key, original, copied)+ assert copied.get('tags', {}).get('language') == original.get('tags', {}).get('language')+ for original, copied in zip(source_subs, subs):+ assert copied['disposition']['forced'] == original['disposition']['forced']+ # A muxed track header alone does not prove that subtitle content survived.+ if subs:+ def subtitle_packets(path):+ return json.loads(subprocess.check_output(['ffprobe', '-v', 'error', '-select_streams', 's',+ '-show_packets', '-show_data_hash', 'sha256', '-show_entries', 'packet=stream_index,pts_time,duration_time,data_hash',+ '-of', 'json', str(path)], env=env, timeout=30)).get('packets', [])+ original_packets, copied_packets = subtitle_packets(source), subtitle_packets(output)+ for original, copied in zip(source_subs, subs):+ first = [p for p in original_packets if p['stream_index'] == original['index']]+ second = [p for p in copied_packets if p['stream_index'] == copied['index']]+ if first:+ assert second, ('Source subtitle packets vanished', original)+ if original['codec_name'] == copied['codec_name'] and 'trim' not in mode:+ assert [p['data_hash'] for p in first] == [p['data_hash'] for p in second], ('Subtitle payload changed', original)+ (LOG / (mode + '-' + tag + '-subtitle-packets.json')).write_text(json.dumps({'source': original_packets, 'output': copied_packets}, indent=2), encoding='utf-8')+ run(['ffmpeg', '-v', 'error', '-i', output, '-map', '0:v', '-map', '0:a?', '-f', 'null', '-'], mode + '-' + tag + '-decode')+ print('PASS', output)diff --git a/scripts/acceptance/export-page-ui.qml b/scripts/acceptance/export-page-ui.qmlnew file mode 100644index 00000000..08b75500--- /dev/null+++ b/scripts/acceptance/export-page-ui.qml@@ -0,0 +1,95 @@+// Loaded only into a task-owned staging copy of Main.qml by the test runner.+// Drives the production bridge/model/worker; never changes installed user data.+import QtQuick+Item {+ id: test+ property string outputDirectory: ""+ property string evidenceDirectory: ""+ property var appWindow: Window.window+ property int step: 0+ property int ticks: 0+ property var ids: []+ property string media: "E:/项目/Veyra/tests/export-page-20261002/media/"+ function find(item,name){if(item.objectName===name)return item;for(const child of item.children||[]){const hit=find(child,name);if(hit)return hit}return null}+ function require(ok,why){if(!ok){console.error("EXPORT_UI_FAIL",step,why);timer.stop();Qt.quit();throw new Error(why)}}+ function done(){console.log("EXPORT_UI_PASS: production model, per-file trim, cancel/retry, frozen batch, mixed failure, sound enabled/disabled, image batch success/failure/cancel");timer.stop();Qt.quit()}+ Timer {+ id: timer+ interval: 200; repeat: true; running: true+ onTriggered: {+ if(++test.ticks>600){test.require(false,"120-second deadline");return}+ if(!test.outputDirectory.length)return+ const model=veyra.exportQueueModel+ if(test.step===0){+ if(test.ticks<5)return+ let files=[];for(let i=0;i<20;++i)files.push(test.media+"tracks.mp4")+ veyra.addExportFiles(files)+ test.require(model.count===20&&!veyra.exportRunning,"add-only contract")+ test.require(model.moveItem(model.get(19).itemId,0),"production model move")+ test.require(model.removeItem(model.get(3).itemId),"production model remove")+ model.clearWaiting();test.require(model.count===0,"production model clear")+ veyra.addExportFiles([test.media+"tracks.mp4",test.media+"font-ass.mkv",test.media+"tracks.mkv"])+ for(let j=0;j<3;++j)test.ids.push(model.get(j).itemId)+ veyra.exportContainer=1;veyra.exportSrTargetIndex=0+ veyra.exportCompletionSound=true+ veyra.previewExportItem(test.ids[0]);test.step=1+ }else if(test.step===1){+ if(!veyra.hasSource||veyra.duration<=0)return+ veyra.exportTrimStart=0.5;veyra.exportTrimEnd=1.5+ test.require(Math.abs(veyra.exportTrimStart-0.5)<0.01,"set first trim")+ veyra.previewExportItem(test.ids[1]);test.step=2+ }else if(test.step===2){+ if(!veyra.hasSource||veyra.duration<=0)return+ test.require(veyra.exportTrimStart===0&&veyra.exportTrimEnd===0,"trim leaked to second item")+ veyra.previewExportItem(test.ids[0])+ test.require(Math.abs(veyra.exportTrimStart-0.5)<0.01&&Math.abs(veyra.exportTrimEnd-1.5)<0.01,"trim not restored")+ model.moveItem(test.ids[2],0)+ veyra.startExport();veyra.cancelExport()+ test.require(veyra.exportReadyCount===3,"cancel lost waiting files")+ test.step=3+ }else if(test.step===3){+ if(veyra.exportRunning)return+ veyra.startExport()+ test.require(veyra.exportRunning,"restart after cancel")+ veyra.addExportFiles([test.media+"tracks.mp4"])+ veyra.previewExportItem(test.ids[1]);test.step=4+ }else if(test.step===4){+ if(veyra.exportRunning)return+ test.require(veyra.exportItems.filter(i=>i.state==="done").length===3,"first batch did not finish all members")+ test.require(veyra.exportReadyCount===1,"late item joined active batch")+ test.step=7+ test.appWindow.contentItem.grabToImage(result=>{+ result.saveToFile(test.evidenceDirectory+"/production-export.png")+ veyra.addExportFiles([test.media+"broken.mkv"])+ veyra.startExport();test.step=5+ })+ }else if(test.step===5){+ if(veyra.exportRunning)return+ test.require(veyra.exportQueueFailures===1,"mixed batch failure missing")+ test.require(veyra.exportItems.some(i=>i.state==="failed"&&i.note.length>0),"specific failure reason missing")+ model.clearWaiting();veyra.exportCompletionSound=false+ veyra.addExportFiles([test.media+"tracks.mp4"]);veyra.startExport();test.step=6+ }else if(test.step===6){+ if(veyra.exportRunning)return+ test.require(veyra.exportItems.every(i=>i.state==="done"),"muted batch failed")+ test.require(!veyra.exportCompletionSound,"sound preference reverted")+ veyra.exportCompletionSound=true+ test.require(veyra.startImageBatch([test.media+"frame-a.png",test.media+"frame-b.png"],test.evidenceDirectory+"/images"),"image batch start refused")+ test.step=8+ }else if(test.step===8){+ if(veyra.imageBatchActive)return+ test.require(veyra.imageBatchDone===2&&veyra.imageBatchFailures===0,"image batch success missing")+ test.require(veyra.startImageBatch([test.media+"frame-a.png",test.media+"frame-b.png"],test.evidenceDirectory+"/images"),"image conflict test refused")+ test.step=9+ }else if(test.step===9){+ if(veyra.imageBatchActive)return+ test.require(veyra.imageBatchDone===0&&veyra.imageBatchFailures===2,"existing image outputs were overwritten")+ test.require(veyra.startImageBatch([test.media+"frame-a.png"],test.evidenceDirectory+"/cancel-images"),"image cancel test refused")+ veyra.cancelImageBatch()+ test.require(!veyra.imageBatchActive,"image cancellation failed")+ veyra.exportCompletionSound=false+ test.done()+ }+ }+ }+}diff --git a/src/engine/ExportJobManager.cpp b/src/engine/ExportJobManager.cppindex f7b154f1..42e5a80d 100644--- a/src/engine/ExportJobManager.cpp+++ b/src/engine/ExportJobManager.cpp@@ -1,6 +1,7 @@#include "veyra/engine/ExportJobManager.h"#include "veyra/engine/EffectChain.h"#include "veyra/engine/VideoExportJob.h"+#include "veyra/engine/ExportStreams.h"#include "veyra/Log.h"#include "veyra/RuntimePaths.h"#include <filesystem>@@ -23,10 +24,11 @@ struct Shared {// chain is fixed-capacity and trivially copyable, so it can cross the// process boundary; a worker that sees another version refuses the job// instead of reading a mismatched layout.- DWORD signature=magic,version=5,bytes=sizeof(Shared); // R5.3 independent colour settings+ DWORD signature=magic,version=6,bytes=sizeof(Shared); // export container / tracks / owned temporaryEnhancementSettings settings;EffectChain chain;- wchar_t input[32768]{},output[32768]{};+ wchar_t input[32768]{},output[32768]{},temporary[32768]{};+ ExportMediaOptions media;unsigned hevc=0,maxFrames=0;int audioStreamIndex=-1;double trimStartSeconds=0.0,trimEndSeconds=0.0;@@ -37,7 +39,23 @@ struct Shared {};static_assert(std::is_trivially_copyable_v<Shared>);void close(HANDLE& h){if(h&&h!=INVALID_HANDLE_VALUE)CloseHandle(h);h=nullptr;}-const wchar_t* label(ExportState s){switch(s){case ExportState::Preparing:return L"正在准备独立导出任务";case ExportState::Running:return L"正在编码";case ExportState::Paused:return L"导出已暂停,观看继续";case ExportState::Finishing:return L"正在封装和保存输出";case ExportState::Succeeded:return L"导出完成";case ExportState::Failed:return L"导出失败;详见独立任务日志,partial已保留";case ExportState::Cancelled:return L"导出已取消;已写入的partial保留";default:return L"尚无导出任务";}}+const wchar_t* label(ExportState s){switch(s){case ExportState::Preparing:return L"正在准备独立导出任务";case ExportState::Running:return L"正在编码";case ExportState::Paused:return L"导出已暂停,观看继续";case ExportState::Finishing:return L"正在封装和保存输出";case ExportState::Cancelling:return L"正在取消并回收任务";case ExportState::Succeeded:return L"导出完成";case ExportState::Failed:return L"导出失败;详见独立任务日志";case ExportState::Cancelled:return L"导出已取消";default:return L"尚无导出任务";}}+}+std::wstring reserveExportTemporaryFile(const std::wstring& output, std::wstring& error) {+ static std::atomic<uint64_t> sequence{0};+ for (int attempt=0; attempt<32; ++attempt) {+ const auto path=std::format(L"{}.veyra-{}-{}-{}.partial",output,GetCurrentProcessId(),GetTickCount64(),++sequence);+ HANDLE file=CreateFileW(path.c_str(),GENERIC_WRITE,0,nullptr,CREATE_NEW,FILE_ATTRIBUTE_NORMAL,nullptr);+ if(file!=INVALID_HANDLE_VALUE){CloseHandle(file);return path;}+ const DWORD code=GetLastError();+ if(code!=ERROR_FILE_EXISTS&&code!=ERROR_ALREADY_EXISTS){error=std::format(L"无法创建临时输出(Windows错误 {}):{}",code,path);return {};}+ }+ error=L"无法为本次导出预留唯一临时文件";return {};+}+bool removeExportTemporaryFile(const std::wstring& path, std::wstring& error) {+ if(path.empty()||DeleteFileW(path.c_str())||GetLastError()==ERROR_FILE_NOT_FOUND)return true;+ error=std::format(L"临时文件清理失败(Windows错误 {}):{}",GetLastError(),path);+ log::warn("export-cleanup",utf8(error));return false;}struct ExportJobManager::Impl {HANDLE mapping=nullptr,process=nullptr,job=nullptr;Shared* shared=nullptr;@@ -66,19 +84,32 @@ ExportJobManager::ExportJobManager():p_(std::make_unique<Impl>()){}// Shutdown is bounded: the job object is KILL_ON_CLOSE, so a worker still// draining NVENC is terminated by clear() after a short grace instead of// stalling process exit for up to five seconds.-ExportJobManager::~ExportJobManager(){cancel();clearQueue();if(p_->process)WaitForSingleObject(p_->process,1000);p_->clear();}-bool ExportJobManager::start(const std::wstring& input,const std::wstring& output,EnhancementSettings settings,bool hevc,unsigned maxFrames,int audioStreamIndex,double trimStartSeconds,double trimEndSeconds,sink::ExportRateControl rateControl){+ExportJobManager::~ExportJobManager(){+ cancel();clearQueue();+ if(p_->process){+ if(WaitForSingleObject(p_->process,1000)==WAIT_TIMEOUT){TerminateJobObject(p_->job,3);WaitForSingleObject(p_->process,1000);}+ if(WaitForSingleObject(p_->process,0)==WAIT_OBJECT_0){std::wstring cleanup;removeExportTemporaryFile(p_->snapshot.temporaryPath,cleanup);}+ }+ p_->clear();+}+bool ExportJobManager::start(const std::wstring& input,const std::wstring& output,EnhancementSettings settings,bool hevc,unsigned maxFrames,int audioStreamIndex,double trimStartSeconds,double trimEndSeconds,sink::ExportRateControl rateControl,ExportMediaOptions media){// Busy means a launched worker not yet collected. Not poll(): polling here// starts the next queued item, which made a queued conflict look "busy"// and dropped it without a failure.- if(p_->shared)return false;p_->clear();+ if(p_->shared&&WaitForSingleObject(p_->process,0)==WAIT_OBJECT_0)poll();+ if(p_->shared){p_->snapshot.message=L"上一任务仍在回收,请等待取消完成";return false;}p_->clear();if(!p_->launchingQueued){p_->queueFailures=0;p_->lastQueueFailure.clear();}const auto failures=p_->queueFailures;const auto lastFailure=p_->lastQueueFailure;p_->snapshot={};p_->snapshot.queueFailures=failures;p_->snapshot.lastQueueFailure=lastFailure;- auto fail=[&](const wchar_t* message){const DWORD error=GetLastError();p_->clear();p_->snapshot.state=ExportState::Failed;p_->snapshot.message=message;log::error("export-worker",std::format("launch failed error={}",error));return false;};+ auto fail=[&](const wchar_t* message){const DWORD error=GetLastError();p_->clear();p_->snapshot.state=ExportState::Failed;p_->snapshot.message=message;std::wstring cleanup;if(!removeExportTemporaryFile(p_->snapshot.temporaryPath,cleanup))p_->snapshot.message+=L"\n"+cleanup;log::error("export-worker",std::format("launch failed error={}",error));return false;};if(input.empty()||output.empty()||input.size()>=32768||output.size()>=32768||!settings.validate().empty()||input.starts_with(L"capture:")||input.starts_with(L"capture2:"))return fail(L"请选择本地视频与有效导出设置");if(rateControl!=sink::ExportRateControl::Cq&&settings.exportBitrateMbps==0)return fail(L"CBR/VBR 需要指定码率;CQ 不使用码率");- if(std::filesystem::exists(output)||std::filesystem::exists(output+L".partial"))return fail(L"输出或partial文件已存在,请选择新文件名");+ if(!media.valid())return fail(L"导出封装或轨道设置无效");+ if(std::filesystem::exists(output))return fail(L"输出文件已存在,请选择新文件名");+ std::wstring reserveError;+ p_->snapshot.temporaryPath=reserveExportTemporaryFile(output,reserveError);+ if(p_->snapshot.temporaryPath.empty())return fail(reserveError.c_str());+ if(p_->snapshot.temporaryPath.size()>=32768)return fail(L"输出路径过长");SECURITY_ATTRIBUTES sa{sizeof(sa),nullptr,TRUE};p_->mapping=CreateFileMappingW(INVALID_HANDLE_VALUE,&sa,PAGE_READWRITE,0,sizeof(Shared),nullptr);if(!p_->mapping)return fail(L"无法创建导出通信资源");@@ -87,6 +118,7 @@ bool ExportJobManager::start(const std::wstring& input,const std::wstring& outpunew(p_->shared) Shared{};auto& s=*p_->shared;s.settings=settings;s.settings.nrPolicy=pipeline::NrSizePolicy::Native;s.chain=toChain(s.settings);s.hevc=hevc;s.maxFrames=maxFrames;s.rateControl=uint32_t(rateControl);s.audioStreamIndex=audioStreamIndex;s.trimStartSeconds=trimStartSeconds;s.trimEndSeconds=trimEndSeconds;+ s.media=media;wcscpy_s(s.temporary,p_->snapshot.temporaryPath.c_str());wcscpy_s(s.input,input.c_str());wcscpy_s(s.output,output.c_str());p_->job=CreateJobObjectW(nullptr,nullptr);JOBOBJECT_EXTENDED_LIMIT_INFORMATION limits{};limits.BasicLimitInformation.LimitFlags=JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;if(!p_->job||!SetInformationJobObject(p_->job,JobObjectExtendedLimitInformation,&limits,sizeof(limits)))return fail(L"无法建立导出进程生命周期");@@ -113,7 +145,7 @@ bool ExportJobManager::enqueue(const std::wstring& input,const std::wstring& out}void ExportJobManager::clearQueue(){p_->queue.clear();}size_t ExportJobManager::queuedCount() const{return p_->queue.size();}-void ExportJobManager::cancel(){if(p_->shared&&p_->snapshot.active()){InterlockedExchange(&p_->shared->cancel,1);if(!p_->cancelAt)p_->cancelAt=GetTickCount64();}p_->queue.clear();}+void ExportJobManager::cancel(){if(p_->shared){InterlockedExchange(&p_->shared->cancel,1);if(!p_->cancelAt)p_->cancelAt=GetTickCount64();p_->snapshot.state=ExportState::Cancelling;p_->snapshot.message=L"正在取消并回收任务";}p_->queue.clear();}void ExportJobManager::pause(bool v){if(p_->shared)InterlockedExchange(&p_->shared->pause,v);}void ExportJobManager::watching(bool v){if(p_->shared)InterlockedExchange(&p_->shared->watching,v);}ExportJobSnapshot ExportJobManager::poll(){@@ -127,6 +159,7 @@ ExportJobSnapshot ExportJobManager::poll(){// Preserve the worker's actual outcome, including codec substitutions.const bool explained=(p_->snapshot.state==ExportState::Failed||p_->snapshot.state==ExportState::Succeeded)&&InterlockedCompareExchange(&s.state,0,0)==LONG(p_->snapshot.state)&&s.message[0];p_->snapshot.message=explained?s.message:label(p_->snapshot.state);+ if(p_->snapshot.state==ExportState::Cancelled){std::wstring cleanup;if(!removeExportTemporaryFile(p_->snapshot.temporaryPath,cleanup))p_->snapshot.message+=L"\n"+cleanup;else p_->snapshot.message=L"导出已取消,可重新开始";}const auto& final=p_->snapshot;log::info("export-worker",std::format("finished jobId={} pid={} exit={} state={} source={} generated={} holds={} encoded={} log={}",final.jobId,final.workerPid,code,int(final.state),final.sourceFrames,final.generated,final.holds,final.encoded,std::filesystem::path(final.workerLog).string()));log::info("export-worker",utf8(final.message));@@ -139,12 +172,16 @@ ExportJobSnapshot ExportJobManager::poll(){return p_->snapshot;}}- if(p_->shared&&InterlockedCompareExchange(&p_->shared->messageLock,1,0)==0){if(p_->shared->message[0])p_->snapshot.message=p_->shared->message;InterlockedExchange(&p_->shared->messageLock,0);}if(p_->snapshot.message.empty()||p_->snapshot.state==ExportState::Paused||p_->snapshot.state==ExportState::Cancelled)p_->snapshot.message=label(p_->snapshot.state);return p_->snapshot;+ // A shared terminal state is only a report. Keep polling until the actual+ // process exits and all parent-owned handles have been collected.+ if(p_->shared&&(p_->cancelAt||!p_->snapshot.active()))p_->snapshot.state=p_->cancelAt?ExportState::Cancelling:ExportState::Finishing;+ if(p_->shared&&InterlockedCompareExchange(&p_->shared->messageLock,1,0)==0){if(p_->shared->message[0])p_->snapshot.message=p_->shared->message;InterlockedExchange(&p_->shared->messageLock,0);}if(p_->snapshot.message.empty()||p_->snapshot.state==ExportState::Paused)p_->snapshot.message=label(p_->snapshot.state);return p_->snapshot;}int runExportWorker(HANDLE mapping){auto s=static_cast<Shared*>(MapViewOfFile(mapping,FILE_MAP_ALL_ACCESS,0,0,sizeof(Shared)));if(!s)return 1;- if(s->signature!=magic||s->version!=5||s->bytes!=sizeof(Shared)||s->audioStreamIndex< -1||s->rateControl>uint32_t(sink::ExportRateControl::Cq)||!std::isfinite(s->trimStartSeconds)||!std::isfinite(s->trimEndSeconds)||s->trimStartSeconds<0||s->trimEndSeconds<0||(s->trimEndSeconds>0&&s->trimEndSeconds<=s->trimStartSeconds)||!s->settings.validate().empty()||s->input[32767]||s->output[32767]){UnmapViewOfFile(s);CloseHandle(mapping);return 1;}+ if(s->signature!=magic||s->version!=6||s->bytes!=sizeof(Shared)||!s->media.valid()||s->audioStreamIndex< -1||s->rateControl>uint32_t(sink::ExportRateControl::Cq)||!std::isfinite(s->trimStartSeconds)||!std::isfinite(s->trimEndSeconds)||s->trimStartSeconds<0||s->trimEndSeconds<0||(s->trimEndSeconds>0&&s->trimEndSeconds<=s->trimStartSeconds)||!s->settings.validate().empty()||s->input[32767]||s->output[32767]||s->temporary[32767]||!s->temporary[0]){UnmapViewOfFile(s);CloseHandle(mapping);return 1;}Logger::instance().openFile((runtime::logsDirectory()/std::format("export-worker-{}.log",GetCurrentProcessId())).wstring());+ ExportStreams::enableWorkerLogging(GetEnvironmentVariableW(L"VEYRA_TEST_EXPORT_FFMPEG_DEBUG",nullptr,0)>0);// The chain is the description of record for this job; the settings struct// stays the runtime input until the executor consumes chains directly.// Re-deriving one from the other must agree, otherwise the job is refused.@@ -161,8 +198,13 @@ int runExportWorker(HANDLE mapping){return !cancel;};auto options=PlayerOptions::from(settings);options.audioStreamIndex=s->audioStreamIndex;options.exportStartSeconds=s->trimStartSeconds;options.exportEndSeconds=s->trimEndSeconds;options.exportRateControl=static_cast<sink::ExportRateControl>(s->rateControl);+ options.exportMedia=s->media;options.exportTemporaryPath=s->temporary;bool ok=false;try{ok=exportVideo(s->input,s->output,options,s->hevc!=0,cancel,[&](double p,const std::wstring& message){if(InterlockedCompareExchange(&s->messageLock,1,0)==0){wcsncpy_s(s->message,message.c_str(),_TRUNCATE);InterlockedExchange(&s->messageLock,0);}InterlockedExchange(&s->progress,LONG(std::clamp(p,0.0,.999)*10000));if(p>=.99)InterlockedExchange(&s->state,LONG(ExportState::Finishing));},s->maxFrames,frameBoundary,[&](const ExportCounts& count){InterlockedExchange64(&s->sourceFrames,count.source);InterlockedExchange64(&s->generated,count.generated);InterlockedExchange64(&s->holds,count.holds);InterlockedExchange64(&s->encoded,count.encoded);});}catch(...){log::error("export-worker","unhandled job exception");}- done=true;monitor.join();InterlockedExchange(&s->state,LONG(ok?ExportState::Succeeded:cancel?ExportState::Cancelled:ExportState::Failed));UnmapViewOfFile(s);CloseHandle(mapping);return ok?0:cancel?3:1;+ done=true;monitor.join();InterlockedExchange(&s->state,LONG(ok?ExportState::Succeeded:cancel?ExportState::Cancelled:ExportState::Failed));+ // Deterministic lifetime regression hook: the real export already finished.+ // No result is fabricated; only process exit is delayed, at most 2 seconds.+ wchar_t delay[16]{};if(GetEnvironmentVariableW(L"VEYRA_TEST_EXPORT_EXIT_DELAY_MS",delay,16))Sleep(std::clamp(_wtoi(delay),0,2000));+ UnmapViewOfFile(s);CloseHandle(mapping);return ok?0:cancel?3:1;}}diff --git a/src/engine/ExportQueue.cpp b/src/engine/ExportQueue.cppnew file mode 100644index 00000000..e1a0fbb8--- /dev/null+++ b/src/engine/ExportQueue.cpp@@ -0,0 +1,148 @@+#include "veyra/engine/ExportQueue.h"+#include <algorithm>+#include <filesystem>+#include <format>++namespace veyra::engine {+ExportQueue::ExportQueue(ExportJobManager& worker):worker_(worker){}+ExportQueue::~ExportQueue(){stopProbe_=true;if(probe_.valid())probe_.wait();}+ExportQueueItem* ExportQueue::mutableItem(uint64_t id){for(auto& item:items_)if(item.id==id)return &item;return nullptr;}+const ExportQueueItem* ExportQueue::find(uint64_t id)const{for(const auto& item:items_)if(item.id==id)return &item;return nullptr;}+bool ExportQueue::editable(const ExportQueueItem& item)const{return item.id!=active_&&item.state!=ExportItemState::Queued;}+uint64_t ExportQueue::add(const std::wstring& input,const std::wstring& output){+ ExportQueueItem item;item.id=++nextId_;item.input=input;item.output=output;item.explicitOutput=!output.empty();item.media.container=container_;+ item.media.audio.policy=ExportTrackPolicy::All;item.media.subtitles.policy=ExportTrackPolicy::All;+ items_.push_back(std::move(item));return nextId_;+}+bool ExportQueue::remove(uint64_t id){+ if(id==active_)return false;+ const auto size=items_.size();+ if(const auto* item=find(id);item&&running_&&item->batch==batch_)interrupted_=true;+ std::erase_if(items_,[&](const auto& item){return item.id==id;});return size!=items_.size();+}+void ExportQueue::clearWaiting(){+ if(running_)interrupted_=true;+ std::erase_if(items_,[&](const auto& item){return item.id!=active_&&(!busy()||item.state==ExportItemState::Ready||item.state==ExportItemState::Queued||item.state==ExportItemState::Cancelled);});+}+bool ExportQueue::move(uint64_t id,int destination){+ if(id==active_||destination<0||size_t(destination)>=items_.size())return false;+ const auto it=std::find_if(items_.begin(),items_.end(),[&](const auto& item){return item.id==id;});+ if(it==items_.end())return false;+ auto item=std::move(*it);items_.erase(it);items_.insert(items_.begin()+destination,std::move(item));return true;+}+bool ExportQueue::retry(uint64_t id){+ auto* item=mutableItem(id);if(!item||!editable(*item)||item->state!=ExportItemState::Failed)return false;+ item->state=ExportItemState::Ready;item->note.clear();item->progress=0;++item->revision;return true;+}+bool ExportQueue::setTrim(uint64_t id,double start,double end){+ auto* item=mutableItem(id);if(!item||!editable(*item)||!std::isfinite(start)||!std::isfinite(end)||start<0||end<0||(end>0&&end<=start))return false;+ if(item->start==start&&item->end==end)return true;+ item->start=start;item->end=end;++item->revision;return true;+}+bool ExportQueue::setTracks(uint64_t id,bool audio,ExportTrackSelection selection){+ auto* item=mutableItem(id);if(!item||!editable(*item)||!selection.valid())return false;+ (audio?item->media.audio:item->media.subtitles)=selection;++item->revision;return true;+}+void ExportQueue::setContainer(ExportContainer container){+ container_=container;+ for(auto& item:items_)if(editable(item)&&item.state!=ExportItemState::Done&&item.media.container!=container){item.media.container=container;if(!item.explicitOutput)item.output.clear();++item.revision;}+}+size_t ExportQueue::readyCount()const{+ return std::count_if(items_.begin(),items_.end(),[](const auto& i){return i.state==ExportItemState::Ready||i.state==ExportItemState::Cancelled;});+}+bool ExportQueue::needsTick()const{+ return busy()||probe_.valid()||std::any_of(items_.begin(),items_.end(),[](const auto& i){return i.inspected!=i.revision;});+}+bool ExportQueue::start(const std::wstring& directory,EnhancementSettings settings,bool hevc,sink::ExportRateControl rate,std::wstring& error){+ if(busy()){error=L"上一批任务仍在执行或回收";return false;}+ if(!readyCount()){error=L"没有待导出文件;失败项请先点击重试";return false;}+ std::error_code ec;+ if(!std::filesystem::is_directory(directory,ec)){error=L"请选择有效的输出目录";return false;}+ // Check directory writability before changing queue state.+ const auto check=reserveExportTemporaryFile((std::filesystem::path(directory)/L".veyra-write-check").wstring(),error);+ if(check.empty())return false;+ if(!removeExportTemporaryFile(check,error))return false;+ ++batch_;successes_=failures_=0;interrupted_=false;directory_=directory;+ for(auto& item:items_)if(!item.explicitOutput&&(item.state==ExportItemState::Ready||item.state==ExportItemState::Cancelled))item.output.clear();+ std::vector<std::filesystem::path> reserved;+ for(const auto& item:items_)if(!item.output.empty())reserved.emplace_back(item.output);+ for(auto& item:items_){+ if(item.state!=ExportItemState::Ready&&item.state!=ExportItemState::Cancelled)continue;+ item.batch=batch_;item.frozen=settings;item.hevc=hevc;item.rate=rate;+ item.state=ExportItemState::Queued;item.progress=0;item.note.clear();+ if(item.output.empty()){+ const auto stem=std::filesystem::path(item.input).stem().wstring()+L"_veyra";+ const auto ext=item.media.container==ExportContainer::Matroska?L".mkv":L".mp4";+ for(unsigned suffix=0;;++suffix){+ auto candidate=std::filesystem::path(directory)/(stem+(suffix?std::format(L" ({})",suffix):L"")+ext);+ const auto used=std::any_of(reserved.begin(),reserved.end(),[&](const auto& path){return _wcsicmp(path.c_str(),candidate.c_str())==0;});+ if(!used&&!std::filesystem::exists(candidate,ec)){item.output=candidate.wstring();reserved.push_back(candidate);break;}+ }+ }+ // Re-probe at Start: the source may have changed since it was added.+ ++item.revision;+ }+ running_=true;status_=L"正在预检本批文件和轨道";return true;+}+void ExportQueue::cancel(){+ running_=false;interrupted_=true;worker_.cancel();snapshot_=worker_.poll();+ for(auto& item:items_)if(item.state==ExportItemState::Queued)item.state=ExportItemState::Ready;+ status_=active_?L"正在取消并回收;等待项保留":L"已停止本批导出;等待项保留";+}+void ExportQueue::finishBatch(){+ running_=false;+ status_=std::format(L"本批完成:成功 {},失败 {}",successes_,failures_);+ if(successes_&&!failures_&&!interrupted_)successEvent_=batch_;+}+bool ExportQueue::tick(){+ bool changed=false;+ if(active_){+ snapshot_=worker_.poll();auto* item=mutableItem(active_);+ if(item&&item->job==snapshot_.jobId){item->progress=snapshot_.progress;item->note=snapshot_.message;changed=true;+ if(!snapshot_.active()){+ if(snapshot_.state==ExportState::Succeeded){item->state=ExportItemState::Done;++successes_;}+ else if(snapshot_.state==ExportState::Cancelled)item->state=ExportItemState::Cancelled;+ else{item->state=ExportItemState::Failed;++failures_;}+ // Batch-wide storage errors stop further launches. The exact+ // reason and owned partial remain on this failed item.+ if(item->note.find(L"(-28)")!=std::wstring::npos||item->note.find(L"错误 112")!=std::wstring::npos){cancel();status_=L"输出磁盘空间不足,已停止本批调度";}+ active_=0;+ }+ }+ }+ if(probe_.valid()&&probe_.wait_for(std::chrono::seconds(0))==std::future_status::ready){+ auto result=probe_.get();auto* item=mutableItem(probingId_);+ if(item&&item->revision==probingRevision_){item->info=std::move(result);item->inspected=item->revision;item->note=item->info.error.empty()?item->info.skipped:item->info.error;changed=true;}+ probingId_=0;+ }+ // Prioritize the first waiting member of the frozen batch. UI reordering+ // changes this order directly; there is no second shadow deque.+ ExportQueueItem* next=nullptr;+ if(running_&&!active_){+ for(auto& item:items_)if(item.state==ExportItemState::Queued&&item.batch==batch_){next=&item;break;}+ if(!next){finishBatch();changed=true;}+ else if(next->inspected==next->revision){+ if(!next->info.error.empty()){+ next->state=ExportItemState::Failed;next->note=next->info.error;++failures_;changed=true;+ }else{+ std::error_code ec;const auto free=std::filesystem::space(directory_,ec);+ if(ec||free.available<1024*1024){cancel();status_=L"输出目录不可用或磁盘空间不足,已停止本批调度";return true;}+ const bool started=worker_.start(next->input,next->output,next->frozen,next->hevc,0,-1,next->start,next->end,next->rate,next->media);+ snapshot_=worker_.poll();next->job=snapshot_.jobId;next->note=snapshot_.message;+ if(started){active_=next->id;next->state=ExportItemState::Running;status_=L"正在按队列顺序导出";}+ else{next->state=ExportItemState::Failed;++failures_;}+ changed=true;+ }+ }+ }+ if(!probe_.valid()){+ if(!next||next->inspected==next->revision){next=nullptr;for(auto& item:items_)if(item.inspected!=item.revision){next=&item;break;}}+ if(next&&next->inspected!=next->revision){+ probingId_=next->id;probingRevision_=next->revision;+ const auto input=next->input;const auto options=next->media;const double start=next->start,end=next->end;+ probe_=std::async(std::launch::async,[this,input,options,start,end]{try{return ExportStreams::probe(input,options,start,end,stopProbe_);}catch(...){ExportMediaInfo result;result.error=L"读取媒体信息失败";return result;}});+ }+ }+ return changed;+}+}diff --git a/src/engine/ExportStreams.cpp b/src/engine/ExportStreams.cppnew file mode 100644index 00000000..d63e808d--- /dev/null+++ b/src/engine/ExportStreams.cpp@@ -0,0 +1,254 @@+#include "veyra/engine/ExportStreams.h"+#include "veyra/Log.h"+#include <windows.h>+#include <algorithm>+#include <cmath>+#include <deque>+#include <format>+#include <limits>+extern "C" {+#include <libavformat/avformat.h>+#include <libavcodec/avcodec.h>+#include <libavcodec/codec_desc.h>+}+namespace veyra::engine {+namespace {+std::string utf8(const std::wstring& s){const int n=WideCharToMultiByte(CP_UTF8,0,s.data(),int(s.size()),nullptr,0,nullptr,nullptr);std::string r(n,0);WideCharToMultiByte(CP_UTF8,0,s.data(),int(s.size()),r.data(),n,nullptr,nullptr);return r;}+std::wstring wide(const char* s){if(!s)return {};const int n=MultiByteToWideChar(CP_UTF8,0,s,-1,nullptr,0);std::wstring r(n,0);MultiByteToWideChar(CP_UTF8,0,s,-1,r.data(),n);if(!r.empty())r.pop_back();return r;}+std::string metadata(AVDictionary* m,const char* key){const auto e=av_dict_get(m,key,nullptr,0);return e?e->value:"";}+bool avError(std::wstring& error,const wchar_t* stage,int code){char detail[AV_ERROR_MAX_STRING_SIZE]{};av_strerror(code,detail,sizeof(detail));error=std::format(L"{}:{}({})",stage,wide(detail),code);log::error("export-streams",utf8(error));return false;}+bool textSubtitle(AVCodecID id){const auto d=avcodec_descriptor_get(id);return d&&(d->props&AV_CODEC_PROP_TEXT_SUB);}+bool validPgsPacket(const AVPacket& packet){+ // Some Matroska compression methods are unavailable in the shipped media+ // library. Its demuxer can return compressed bytes after only logging an+ // error; pgs_frame_merge then drops them without an error return. Validate+ // segment framing before passing packets to that filter, never claim that+ // an empty output track preserved the source subtitles.+ if(packet.size<=0)return false;+ size_t offset=0;+ while(offset<size_t(packet.size)){+ if(size_t(packet.size)-offset<3)return false;+ const auto* data=packet.data+offset;+ if((data[0]<0x14||data[0]>0x17)&&data[0]!=0x80)return false;+ const size_t length=3+(size_t(data[1])<<8)+data[2];+ if(length>size_t(packet.size)-offset)return false;+ offset+=length;+ }+ return true;+}+struct PacketDelete{void operator()(AVPacket* p)const{av_packet_free(&p);}};+using Packet=std::unique_ptr<AVPacket,PacketDelete>;+void workerAvLog(void* context,int level,const char* format,va_list args){+ if(level>av_log_get_level())return;+ char line[4096]{};int prefix=1;av_log_format_line2(context,level,format,args,line,sizeof(line),&prefix);+ if(level<=AV_LOG_ERROR)log::error("ffmpeg-export",line);else if(level<=AV_LOG_WARNING)log::warn("ffmpeg-export",line);else log::info("ffmpeg-export",line);+}+}+void ExportStreams::enableWorkerLogging(bool detailed){av_log_set_callback(workerAvLog);av_log_set_level(detailed?AV_LOG_DEBUG:AV_LOG_WARNING);}+struct ExportStreams::Impl {+ struct Track {+ AVStream* source=nullptr;AVStream* target=nullptr;+ AVCodecContext* decoder=nullptr;AVCodecContext* encoder=nullptr;+ bool subtitle=false,text=false;+ uint64_t read=0,written=0;+ ~Track(){avcodec_free_context(&decoder);avcodec_free_context(&encoder);}+ };+ struct Buffered {Packet packet;int index;double time,duration;};+ AVFormatContext* input=nullptr;AVFormatContext* output=nullptr;+ std::vector<std::unique_ptr<Track>> tracks;+ std::deque<Buffered> pending;+ ExportMediaInfo info;+ std::atomic<bool>* cancel=nullptr;+ ULONGLONG deadline=0;+ int video=-1;+ bool eof=false;+ double watermark=-std::numeric_limits<double>::infinity(),start=0,end=0;+ size_t bufferedBytes=0;+ ~Impl(){pending.clear();tracks.clear();avformat_close_input(&input);}+ static int interrupted(void* opaque){auto& p=*static_cast<Impl*>(opaque);return (p.cancel&&p.cancel->load())||(p.deadline&&GetTickCount64()>p.deadline);}+};+ExportStreams::ExportStreams():p_(std::make_unique<Impl>()){}+ExportStreams::~ExportStreams()=default;+const ExportMediaInfo& ExportStreams::info()const{return p_->info;}+bool ExportStreams::prepare(const std::wstring& path,AVFormatContext* output,const ExportMediaOptions& options,+ int defaultAudio,double start,double end,std::atomic<bool>& cancel,std::wstring& error){+ auto& p=*p_;p.output=output;p.cancel=&cancel;p.start=start;p.end=end;p.deadline=GetTickCount64()+15000;+ p.input=avformat_alloc_context();if(!p.input)return avError(error,L"创建轨道读取器",AVERROR(ENOMEM));+ p.input->interrupt_callback={Impl::interrupted,&p};+ int rc=avformat_open_input(&p.input,utf8(path).c_str(),nullptr,nullptr);+ if(rc<0)return avError(error,L"打开源轨道",rc);+ rc=avformat_find_stream_info(p.input,nullptr);if(rc<0)return avError(error,L"读取源轨道",rc);+ p.info.duration=p.input->duration==AV_NOPTS_VALUE?0:p.input->duration/double(AV_TIME_BASE);+ p.video=av_find_best_stream(p.input,AVMEDIA_TYPE_VIDEO,-1,-1,nullptr,0);+ if(p.video<0){error=L"文件中没有可导出的视频轨道";return false;}+ p.tracks.resize(p.input->nb_streams);+ if(options.audio.policy==ExportTrackPolicy::Default&&defaultAudio>=0&&+ (unsigned(defaultAudio)>=p.input->nb_streams||p.input->streams[defaultAudio]->codecpar->codec_type!=AVMEDIA_TYPE_AUDIO)){+ error=std::format(L"所选音轨 {} 已不存在或类型不匹配",defaultAudio);return false;+ }+ if(defaultAudio<0)defaultAudio=av_find_best_stream(p.input,AVMEDIA_TYPE_AUDIO,-1,-1,nullptr,0);+ auto chosen=[](const ExportTrackSelection& s,int index,bool isDefault){return s.policy==ExportTrackPolicy::All||(s.policy==ExportTrackPolicy::Selected&&s.contains(index))||(s.policy==ExportTrackPolicy::Default&&isDefault);};+ const bool mkv=options.container==ExportContainer::Matroska;+ bool hasSubtitles=false,anySkipped=false;unsigned skippedAudio=0,keptAudio=0;+ for(unsigned i=0;i<p.input->nb_streams;++i){+ auto* source=p.input->streams[i];const auto* cp=source->codecpar;+ const bool audio=cp->codec_type==AVMEDIA_TYPE_AUDIO,subtitle=cp->codec_type==AVMEDIA_TYPE_SUBTITLE;+ if(!audio&&!subtitle)continue;+ ExportTrackInfo t;t.index=int(i);t.audio=audio;t.subtitle=subtitle;t.channels=cp->ch_layout.nb_channels;+ t.codec=avcodec_get_name(cp->codec_id);t.language=metadata(source->metadata,"language");t.title=metadata(source->metadata,"title");+ t.defaultTrack=(source->disposition&AV_DISPOSITION_DEFAULT)!=0;t.forced=(source->disposition&AV_DISPOSITION_FORCED)!=0;+ t.selected=chosen(audio?options.audio:options.subtitles,int(i),audio&&int(i)==defaultAudio);+ t.action=t.selected?L"原样保留":L"不保留";+ const bool text=subtitle&&textSubtitle(cp->codec_id);+ AVCodecID targetCodec=cp->codec_id;+ if(t.selected){+ if(subtitle&&!text&&(start>0||end>0)){t.compatible=false;t.action=L"图片字幕剪辑尚不支持,请保留整片或排除此轨";}+ else if(avformat_query_codec(output->oformat,cp->codec_id,FF_COMPLIANCE_NORMAL)<=0){+ if(text&&options.convertTextSubtitles){targetCodec=mkv?AV_CODEC_ID_ASS:AV_CODEC_ID_MOV_TEXT;t.converted=true;t.action=mkv?L"转换为 ASS 文本字幕":L"转换为 MP4 文本字幕(复杂样式不保留)";}+ else{t.compatible=false;t.action=mkv?L"MKV 不支持直接保留此编码,请排除此轨":L"MP4 不支持直接保留此编码,请选择 MKV 或排除此轨";}+ }+ if(!t.compatible){+ // "All" is the default and means everything this container can+ // hold: skip what it cannot and say so before start. A track the+ // user picked by hand still fails the export instead of vanishing.+ const bool all=(audio?options.audio:options.subtitles).policy==ExportTrackPolicy::All;+ auto& report=all?p.info.skipped:error;+ if(!report.empty())report+=L"\n";+ report+=std::format(L"轨道 {}({}):{}",i,wide(t.codec.c_str()),t.action);+ if(all){t.action+=L"(已跳过)";anySkipped=true;skippedAudio+=audio;}+ }+ }+ p.info.tracks.push_back(t);+ if(!t.selected||!t.compatible)continue;+ auto track=std::make_unique<Impl::Track>();track->source=source;track->subtitle=subtitle;track->text=text;+ track->target=avformat_new_stream(output,nullptr);if(!track->target)return avError(error,L"创建输出轨道",AVERROR(ENOMEM));+ if(t.converted){+ const auto* decoder=avcodec_find_decoder(cp->codec_id);const auto* encoder=avcodec_find_encoder(targetCodec);+ if(!decoder||!encoder){error=std::format(L"轨道 {} 所需字幕编解码器不可用",i);return false;}+ track->decoder=avcodec_alloc_context3(decoder);track->encoder=avcodec_alloc_context3(encoder);+ if(!track->decoder||!track->encoder)return avError(error,L"分配字幕编解码器",AVERROR(ENOMEM));+ rc=avcodec_parameters_to_context(track->decoder,cp);if(rc<0)return avError(error,L"读取字幕参数",rc);+ track->decoder->pkt_timebase=source->time_base;+ rc=avcodec_open2(track->decoder,decoder,nullptr);if(rc<0)return avError(error,L"打开字幕解码器",rc);+ auto* enc=track->encoder;enc->time_base={1,1000};enc->flags|=AV_CODEC_FLAG_GLOBAL_HEADER;+ if(track->decoder->subtitle_header_size){+ enc->subtitle_header_size=track->decoder->subtitle_header_size;+ enc->subtitle_header=static_cast<uint8_t*>(av_mallocz(enc->subtitle_header_size+AV_INPUT_BUFFER_PADDING_SIZE));+ if(!enc->subtitle_header)return avError(error,L"分配字幕头",AVERROR(ENOMEM));+ memcpy(enc->subtitle_header,track->decoder->subtitle_header,enc->subtitle_header_size);+ }+ rc=avcodec_open2(enc,encoder,nullptr);if(rc<0)return avError(error,L"打开字幕编码器",rc);+ rc=avcodec_parameters_from_context(track->target->codecpar,enc);+ }else rc=avcodec_parameters_copy(track->target->codecpar,cp);+ if(rc<0)return avError(error,L"复制轨道参数",rc);+ track->target->codecpar->codec_tag=0;track->target->time_base=source->time_base;+ if(audio&&start>0)track->target->codecpar->initial_padding=0;+ track->target->disposition=source->disposition;+ av_dict_copy(&track->target->metadata,source->metadata,0);+ // Source-duration tags become false after a trim. The muxer derives new+ // duration from packets while language/title/default/forced remain intact.+ av_dict_set(&track->target->metadata,"DURATION",nullptr,0);+ hasSubtitles|=subtitle;keptAudio+=audio;p.tracks[i]=std::move(track);+ log::info("export-streams",std::format("stream={} codec={} text={} action={}",i,t.codec,text,utf8(t.action)));+ }+ // Validate explicit selections against this file, not against preview tracks.+ for(const auto* s:{&options.audio,&options.subtitles})if(s->policy==ExportTrackPolicy::Selected){+ for(uint32_t j=0;j<s->count;++j){const int index=s->indices[j];const auto type=s==&options.audio?AVMEDIA_TYPE_AUDIO:AVMEDIA_TYPE_SUBTITLE;+ if(index<0||unsigned(index)>=p.input->nb_streams||p.input->streams[index]->codecpar->codec_type!=type){error=std::format(L"所选轨道 {} 已不存在或类型不匹配",index);return false;}+ }+ }+ if(!error.empty())return false;+ if(anySkipped){+ p.info.skipped=std::wstring(L"以下轨道当前封装无法保留,导出时跳过")+(mkv?L"":L"(改用 MKV 可保留更多)")+L":\n"+p.info.skipped;+ if(skippedAudio&&!keptAudio)p.info.skipped+=L"\n注意:导出的视频将没有声音";+ log::warn("export-streams",utf8(p.info.skipped));+ }+ if(mkv&&hasSubtitles)for(unsigned i=0;i<p.input->nb_streams;++i){+ auto* source=p.input->streams[i];const auto* cp=source->codecpar;+ if(cp->codec_type!=AVMEDIA_TYPE_ATTACHMENT||(cp->codec_id!=AV_CODEC_ID_TTF&&cp->codec_id!=AV_CODEC_ID_OTF))continue;+ auto* target=avformat_new_stream(output,nullptr);if(!target)return avError(error,L"创建字体附件",AVERROR(ENOMEM));+ rc=avcodec_parameters_copy(target->codecpar,cp);if(rc<0)return avError(error,L"复制字体附件",rc);+ target->codecpar->codec_tag=0;av_dict_copy(&target->metadata,source->metadata,0);+ }+ av_dict_copy(&output->metadata,p.input->metadata,0);av_dict_set(&output->metadata,"DURATION",nullptr,0);+ output->max_interleave_delta=AV_TIME_BASE; // sparse subtitle tracks cannot buffer the whole film+ output->error_recognition|=AV_EF_EXPLODE; // a failing automatic bitstream filter must never silently discard a track+ p.deadline=0;return true;+}+bool ExportStreams::writeUntil(double seconds,double origin,bool final,std::wstring& error){+ auto& p=*p_;p.deadline=GetTickCount64()+15000;+ // Read a bounded amount beyond video progress, using video packets as the+ // demux watermark. A subtitle seven minutes ahead never blocks audio.+ while(!p.eof&&p.watermark<origin+seconds+1.0){+ if(p.cancel->load()){error=L"导出已取消";return false;}+ Packet pkt(av_packet_alloc());if(!pkt)return avError(error,L"分配轨道数据包",AVERROR(ENOMEM));+ const int rc=av_read_frame(p.input,pkt.get());if(rc==AVERROR_EOF){p.eof=true;break;}if(rc<0)return avError(error,L"读取附属轨道",rc);+ const int index=pkt->stream_index;const auto* source=p.input->streams[index];+ const int64_t ts=pkt->pts!=AV_NOPTS_VALUE?pkt->pts:pkt->dts;+ const double time=ts==AV_NOPTS_VALUE?0:ts*av_q2d(source->time_base);+ if(index==p.video&&ts!=AV_NOPTS_VALUE)p.watermark=time;+ if(!p.tracks[index])continue;+ if(ts==AV_NOPTS_VALUE){error=std::format(L"轨道 {} 数据包缺少时间戳,无法保证同步",index);return false;}+ double duration=pkt->duration*av_q2d(source->time_base);+ auto& track=*p.tracks[index];+ ++track.read;+ if(track.source->codecpar->codec_id==AV_CODEC_ID_HDMV_PGS_SUBTITLE&&!validPgsPacket(*pkt)){+ error=std::format(L"轨道 {} 的 PGS 数据无效,或源文件的轨道压缩方式不受当前媒体库支持;请先无损重新封装源文件,或排除此字幕轨道",index);+ return false;+ }+ if(track.encoder){+ AVSubtitle sub{};int got=0;+ const int decoded=avcodec_decode_subtitle2(track.decoder,&sub,&got,pkt.get());+ if(decoded<0){avsubtitle_free(&sub);return avError(error,L"解码字幕",decoded);}+ if(!got){avsubtitle_free(&sub);continue;}+ if(sub.end_display_time>sub.start_display_time)duration=(sub.end_display_time-sub.start_display_time)/1000.0;+ std::vector<uint8_t> bytes(1024*1024);+ const int encoded=avcodec_encode_subtitle(track.encoder,bytes.data(),int(bytes.size()),&sub);avsubtitle_free(&sub);+ if(encoded<0)return avError(error,L"转换字幕",encoded);+ if(!encoded)continue;+ Packet converted(av_packet_alloc());if(!converted||av_new_packet(converted.get(),encoded)<0)return avError(error,L"分配转换字幕",AVERROR(ENOMEM));+ memcpy(converted->data,bytes.data(),encoded);converted->flags=pkt->flags;converted->pts=pkt->pts;converted->dts=pkt->dts;converted->duration=pkt->duration;+ pkt=std::move(converted);+ }+ const double relative=time-origin;+ if(track.subtitle&&track.text){if(relative+duration<=0)continue;}+ else if(relative<0&&(p.start>0||relative+duration< -0.00001))continue;+ // Retain the original negative priming packet ending at zero. Dropping+ // it while preserving Matroska CodecDelay skips audible samples twice.+ if(p.end>0&&time>=p.end)continue;+ p.bufferedBytes+=pkt->size;+ if(p.bufferedBytes>64*1024*1024||p.pending.size()>=16384){error=L"源文件轨道交织跨度过大,超过 64 MiB/16384 包的安全缓冲上限";return false;}+ p.pending.push_back({std::move(pkt),index,relative,duration});+ }+ for(auto it=p.pending.begin();it!=p.pending.end();){+ auto& track=*p.tracks[it->index];+ double start=it->time,end=start+it->duration;+ if(p.end>0)end=std::min(end,p.end-origin);+ // Hold text until its end is known to fit the video. At final drain a+ // crossing cue is clipped, including cues that started before the trim.+ const bool due=final||(track.subtitle&&track.text?end<=seconds:start<seconds);+ if(!due){++it;continue;}+ if(final)end=std::min(end,seconds);+ const size_t bytes=it->packet->size;+ auto* pkt=it->packet.get();+ if(start<seconds&&(!track.text||end>std::max(0.0,start))){+ const auto tb=track.source->time_base;+ if(track.text){start=std::max(0.0,start);pkt->pts=pkt->dts=av_rescale_q(int64_t(std::llround(start*1000000)),{1,1000000},tb);pkt->duration=std::max<int64_t>(1,av_rescale_q(int64_t(std::llround((end-start)*1000000)),{1,1000000},tb));}+ else{const int64_t offset=av_rescale_q(int64_t(std::llround(origin*1000000)),{1,1000000},tb);if(pkt->pts!=AV_NOPTS_VALUE)pkt->pts-=offset;if(pkt->dts!=AV_NOPTS_VALUE)pkt->dts-=offset;}+ av_packet_rescale_ts(pkt,tb,track.target->time_base);pkt->stream_index=track.target->index;pkt->pos=-1;+ const int rc=av_interleaved_write_frame(p.output,pkt);if(rc<0)return avError(error,L"写入附属轨道",rc);+ ++track.written;+ }+ p.bufferedBytes-=bytes;it=p.pending.erase(it);+ }+ if(final)for(size_t index=0;index<p.tracks.size();++index)if(p.tracks[index])log::info("export-streams",std::format("drained stream={} read={} written={} videoEnd={} origin={}",index,p.tracks[index]->read,p.tracks[index]->written,seconds,origin));+ p.deadline=0;return true;+}+ExportMediaInfo ExportStreams::probe(const std::wstring& input,const ExportMediaOptions& options,double start,double end,std::atomic<bool>& cancel){+ ExportMediaInfo result;AVFormatContext* output=nullptr;+ const int rc=avformat_alloc_output_context2(&output,nullptr,options.container==ExportContainer::Matroska?"matroska":"mp4",nullptr);+ if(rc<0||!output){result.error=L"输出封装器不可用";return result;}+ {ExportStreams streams;std::wstring error;streams.prepare(input,output,options,-1,start,end,cancel,error);result=streams.info();result.error=error;}+ avformat_free_context(output);return result;+}+}diff --git a/src/engine/VideoExportJob.cpp b/src/engine/VideoExportJob.cppindex da987def..10b0d86f 100644--- a/src/engine/VideoExportJob.cpp+++ b/src/engine/VideoExportJob.cpp@@ -1,4 +1,5 @@#include "veyra/engine/VideoExportJob.h"+#include "veyra/engine/ExportStreams.h"#include "veyra/source/MediaFileSource.h"#include "veyra/pipeline/EnhanceGraph.h"#include "veyra/pipeline/ResolutionPlan.h"@@ -23,7 +24,8 @@ namespace veyra::engine {namespace { std::string utf8(const std::wstring& s){const int n=WideCharToMultiByte(CP_UTF8,0,s.data(),int(s.size()),nullptr,0,nullptr,nullptr);std::string r(n,0);WideCharToMultiByte(CP_UTF8,0,s.data(),int(s.size()),r.data(),n,nullptr,nullptr);return r;} }bool exportVideo(const std::wstring& input,const std::wstring& output,PlayerOptions options,bool hevc,std::atomic<bool>& cancel,const std::function<void(double,const std::wstring&)>& progress,unsigned maxFrames,const std::function<bool()>& frameBoundary,const std::function<void(const ExportCounts&)>& counts){if(!std::isfinite(options.exportStartSeconds)||!std::isfinite(options.exportEndSeconds)||options.exportStartSeconds<0||options.exportEndSeconds<0||(options.exportEndSeconds>0&&options.exportEndSeconds<=options.exportStartSeconds)){progress(0,L"导出剪辑范围无效");return false;}- if(std::filesystem::exists(output)||std::filesystem::exists(output+L".partial")){progress(0,L"目标或partial文件已存在,请使用其他名称");return false;}+ if(std::filesystem::exists(output)){progress(0,L"目标文件已存在,请使用其他名称");return false;}+ if(cancel){progress(0,L"导出已取消");return false;}// XeSS still has no exposed output texture. FSR preview now does, but// FSR encoder/HDR/cadence acceptance remains a separate task. Preserve the// established, explicit DLSS substitution for this release candidate.@@ -37,8 +39,8 @@ bool exportVideo(const std::wstring& input,const std::wstring& output,PlayerOpti}gfx::D3D12DeviceContext ctx;gfx::CommandSlotRing ring;source::MediaFileSource source;pipeline::EnhanceGraph graph(ctx,ring);std::unique_ptr<sink::VideoEncoder> encoder;- AVFormatContext *mux=nullptr,*audioInput=nullptr;AVStream* videoStream=nullptr;AVStream* audioStream=nullptr;AVPacket* audioPacket=av_packet_alloc();- int audioIndex=-1;bool audioPending=false,audioEof=false,ok=false,headerWritten=false;int64_t written=0;double audioEndSeconds=0,videoOriginSeconds=0;+ AVFormatContext* mux=nullptr;AVStream* videoStream=nullptr;ExportStreams streams;+ bool ok=false,headerWritten=false;int64_t written=0;double audioEndSeconds=0,videoOriginSeconds=0;uint64_t repairedTimestamps=0;std::wstring encoderName;std::wstring failureReason;@@ -48,7 +50,8 @@ bool exportVideo(const std::wstring& input,const std::wstring& output,PlayerOptiveyra::log::error("export",std::format("stage={} code={} detail={}",utf8(stage),code,error));return false;};- const auto partial=output+L".partial";+ const auto partial=options.exportTemporaryPath.empty()?reserveExportTemporaryFile(output,failureReason):options.exportTemporaryPath;+ if(partial.empty()){progress(0,failureReason);return false;}try { do {Status st=Status::Ok;gfx::DeviceContextDesc dd;dd.commandSlotCount=6;if(!ctx.initialize(dd,st)||!ring.initialize(ctx.device(),ctx.directQueue(),ctx.fence(),ctx.fenceEvent(),6,st))break;@@ -66,14 +69,14 @@ bool exportVideo(const std::wstring& input,const std::wstring& output,PlayerOpticonst double requestedEnd=options.exportEndSeconds;if(requestedStart>0&& !source.seek(pipeline::Rational{static_cast<int64_t>(std::llround(requestedStart*1000000.0)),1000000})){failureReason=L"导出无法定位到剪辑入点";break;}pipeline::FramePacket firstPacket;const AVFrame* firstFrame=nullptr;bool firstReady=false;- while(!firstReady){+ while(!firstReady&&!cancel){const auto firstStatus=source.read(firstPacket,&firstFrame);if(firstStatus!=source::SourceReadStatus::Frame||!firstFrame){failureReason=firstStatus==source::SourceReadStatus::Eos?L"剪辑入点已超过源视频时长":L"导出预读首帧失败";break;}const double firstPts=firstPacket.pts.toDouble();firstReady=requestedStart<=0||firstPacket.pts.isUnknown()||!std::isfinite(firstPts)||firstPts>=requestedStart;if(!firstReady)firstFrame=nullptr;}- if(!firstReady)break;+ if(!firstReady||cancel)break;info=source.info(); // retain this frame for the export, without decoding it againint rateNum=info.nominalRateNum,rateDen=info.nominalRateDen;if(rateNum<=0||rateDen<=0){rateNum=30;rateDen=1;veyra::log::warn("export-timeline","missing nominal rate; encoder configured at 30 fps, source timestamps retained");}@@ -128,12 +131,13 @@ bool exportVideo(const std::wstring& input,const std::wstring& output,PlayerOpti}} else startGraph(false,1);if(!graphReady){if(failureReason.empty())failureReason=L"增强管线初始化失败,请查看诊断";break;}+ if(cancel)break;if(gd.hdrOutput&&!hevc){hevc=true;fgNote+=fgNote.empty()?L"HDR 视频自动使用 HEVC Main10 编码":L";HDR 视频自动使用 HEVC Main10 编码";}if(!fgNote.empty())progress(0,fgNote);const AVRational rate=av_mul_q({rateNum,rateDen},{int(options.fg?options.fgMultiplier:1),1});constexpr AVRational mediaTimeBase{1,1000000};veyra::log::info("export-timeline",std::format("source-timed export nominal={}/{} encoder={}/{} fg={} backend={} note={} (no CFR preflight or output decode verification)",rateNum,rateDen,rate.num,rate.den,options.fg?options.fgMultiplier:1,frameGenerationBackendName(options.settings.frameGenerationBackend),utf8(fgNote)));- if(avformat_alloc_output_context2(&mux,nullptr,"mp4",utf8(partial).c_str())<0||!mux)break;+ if(avformat_alloc_output_context2(&mux,nullptr,options.exportMedia.container==ExportContainer::Matroska?"matroska":"mp4",utf8(partial).c_str())<0||!mux)break;videoStream=avformat_new_stream(mux,nullptr);if(!videoStream)break;videoStream->time_base=mediaTimeBase;videoStream->avg_frame_rate=rate;auto* cp=videoStream->codecpar;cp->codec_type=AVMEDIA_TYPE_VIDEO;cp->codec_id=hevc?AV_CODEC_ID_HEVC:AV_CODEC_ID_H264;cp->width=gd.workWidth;cp->height=gd.workHeight;cp->format=AV_PIX_FMT_YUV420P;cp->color_range=AVCOL_RANGE_MPEG;cp->color_space=AVCOL_SPC_BT709;cp->color_primaries=AVCOL_PRI_BT709;cp->color_trc=AVCOL_TRC_IEC61966_2_1;if(gd.hdrOutput){cp->format=AV_PIX_FMT_YUV420P10LE;cp->color_space=AVCOL_SPC_BT2020_NCL;cp->color_primaries=AVCOL_PRI_BT2020;cp->color_trc=AVCOL_TRC_SMPTE2084;cp->profile=AV_PROFILE_HEVC_MAIN_10;}@@ -148,28 +152,9 @@ bool exportVideo(const std::wstring& input,const std::wstring& output,PlayerOpticll->MaxFALL=unsigned(info.color.hdrMaxFallNits);}else failureReason=L"无法写入内容亮度元数据(MaxCLL/MaxFALL)";}- auto inputUtf8=utf8(input);- if(avformat_open_input(&audioInput,inputUtf8.c_str(),nullptr,nullptr)<0||avformat_find_stream_info(audioInput,nullptr)<0){progress(0,L"无法读取源音轨信息,已停止导出");break;}- {- audioIndex=av_find_best_stream(audioInput,AVMEDIA_TYPE_AUDIO,-1,-1,nullptr,0);- if(options.audioStreamIndex>=0){- if(unsigned(options.audioStreamIndex)>=audioInput->nb_streams||audioInput->streams[options.audioStreamIndex]->codecpar->codec_type!=AVMEDIA_TYPE_AUDIO){progress(0,L"选定音轨已不存在,已停止导出");break;}- audioIndex=options.audioStreamIndex;- }- log::info("export-audio",std::format("selected stream={}",audioIndex));- if(audioIndex>=0){auto* acp=audioInput->streams[audioIndex]->codecpar;- audioStream=avformat_new_stream(mux,nullptr);if(!audioStream||avcodec_parameters_copy(audioStream->codecpar,acp)<0)break;audioStream->codecpar->codec_tag=0;audioStream->time_base=audioInput->streams[audioIndex]->time_base;- av_dict_copy(&audioStream->metadata,audioInput->streams[audioIndex]->metadata,0);- }- av_dict_copy(&mux->metadata,audioInput->metadata,0);- }- auto writeAudioUntil=[&](double seconds){if(!audioStream)return true;- for(;;){if(!audioPending){if(audioEof)return true;av_packet_unref(audioPacket);const int readResult=av_read_frame(audioInput,audioPacket);if(readResult==AVERROR_EOF){audioEof=true;return true;}if(readResult<0)return failAv(L"读取音轨",readResult);if(audioPacket->stream_index!=audioIndex)continue;audioPending=true;}- const auto tb=audioInput->streams[audioIndex]->time_base;const int64_t ts=audioPacket->pts!=AV_NOPTS_VALUE?audioPacket->pts:audioPacket->dts;const double time=ts==AV_NOPTS_VALUE?0:ts*av_q2d(tb)-videoOriginSeconds;if(time>seconds)return true;if(time<0){audioPending=false;continue;}- const int64_t origin=av_rescale_q(static_cast<int64_t>(videoOriginSeconds*1000000),{1,1000000},tb);- if(audioPacket->pts!=AV_NOPTS_VALUE)audioPacket->pts-=origin;if(audioPacket->dts!=AV_NOPTS_VALUE)audioPacket->dts-=origin;- av_packet_rescale_ts(audioPacket,tb,audioStream->time_base);audioPacket->stream_index=audioStream->index;audioPacket->pos=-1;audioPending=false;const int rc=av_interleaved_write_frame(mux,audioPacket);if(rc<0)return failAv(L"写入音轨",rc);- }};+ if(!streams.prepare(input,mux,options.exportMedia,options.audioStreamIndex,requestedStart,requestedEnd,cancel,failureReason))break;+ if(!streams.info().skipped.empty()){const std::wstring note=L"部分轨道当前封装装不下,未保留(详见队列说明)";fgNote+=fgNote.empty()?note:L";"+note;progress(0,fgNote);}+ auto writeAudioUntil=[&](double seconds,bool final=false){return streams.writeUntil(seconds,videoOriginSeconds,final,failureReason);};// Encoders retain ordinal timestamps; only the bounded in-flight queue// maps them to media time. Hold one compressed packet for its duration.std::deque<std::pair<int64_t,int64_t>> timestamps;@@ -211,7 +196,7 @@ bool exportVideo(const std::wstring& input,const std::wstring& output,PlayerOptiint muxResult=avio_open(&mux->pb,utf8(partial).c_str(),AVIO_FLAG_WRITE);if(muxResult<0){failAv(L"创建输出文件",muxResult);break;}muxResult=avformat_write_header(mux,nullptr);- if(muxResult<0){failAv(L"写入MP4文件头",muxResult);break;}headerWritten=true;+ if(muxResult<0){failAv(L"写入封装文件头",muxResult);break;}headerWritten=true;uint64_t sourceCount=0,generatedCount=0,holdCount=0;int64_t outputIndex=0;bool error=false;std::shared_ptr<pipeline::FrameLease> lastReal;double previousPts=0;int64_t lastOutputUs=-1;const uint32_t multiplier=options.fg?options.fgMultiplier:1u;@@ -228,7 +213,7 @@ bool exportVideo(const std::wstring& input,const std::wstring& output,PlayerOptidouble sourcePts=packet.pts.toDouble();if(sourceCount==0)videoOriginSeconds=!packet.pts.isUnknown()&&std::isfinite(sourcePts)?sourcePts:0;double pts=sourcePts-videoOriginSeconds;- if(requestedEnd>0&&pts>requestedEnd-requestedStart)break;+ if(requestedEnd>0&&sourcePts>=requestedEnd)break;const bool repairPts=packet.pts.isUnknown()||!std::isfinite(pts)||(sourceCount&&pts<=previousPts);if(repairPts){pts=sourceCount?previousPts+sourceInterval:0;++repairedTimestamps;@@ -264,17 +249,26 @@ bool exportVideo(const std::wstring& input,const std::wstring& output,PlayerOptiveyra::log::info("export-counts",std::format("source={} generated={} hold={} output={} multiplier={} repairedTimestamps={} backend={} encoder={} bitrateMbps={} note={} (holds are not DLSSG)",sourceCount,generatedCount,holdCount,outputIndex,multiplier,repairedTimestamps,frameGenerationBackendName(options.settings.frameGenerationBackend),std::string(sink::encoderBackendName(encoder->backend())),options.settings.exportBitrateMbps,utf8(fgNote)));progress(.99,L"正在收尾:等待编码器输出剩余帧");if(!encoder->finish()){if(failureReason.empty())failureReason=L"编码器收尾失败,请查看编码器诊断";break;}- if(!flushVideo(lastOutputUs+std::max<int64_t>(1,int64_t(std::llround(sourceInterval*1000000/multiplier)))))break;- if(!writeAudioUntil(audioEndSeconds))break;- progress(.995,L"正在收尾:写入MP4索引");+ const int64_t estimatedEnd=lastOutputUs+std::max<int64_t>(1,int64_t(std::llround(sourceInterval*1000000/multiplier)));+ const int64_t finalEnd=requestedEnd>0?std::min(estimatedEnd,int64_t(std::llround((requestedEnd-videoOriginSeconds)*1000000))):estimatedEnd;+ if(!flushVideo(finalEnd))break;+ if(!writeAudioUntil(audioEndSeconds,true))break;+ progress(.995,L"正在收尾:写入封装索引");muxResult=av_write_trailer(mux);- if(muxResult<0){failAv(L"写入MP4索引",muxResult);break;}+ if(muxResult<0){failAv(L"写入封装索引",muxResult);break;}ok=written>0;if(counts)counts({sourceCount,generatedCount,holdCount,uint64_t(written)});}while(false); }catch(const std::exception& e){veyra::log::error("export",std::format("exception: {}",e.what()));failureReason=L"导出异常,请查看诊断";ok=false;}- encoder.reset();if(mux){if(mux->pb){const int rc=avio_closep(&mux->pb);if(rc<0){failAv(L"刷新并关闭输出文件",rc);ok=false;}}avformat_free_context(mux);}if(audioInput)avformat_close_input(&audioInput);av_packet_free(&audioPacket);+ encoder.reset();if(mux){if(mux->pb){const int rc=avio_closep(&mux->pb);if(rc<0){failAv(L"刷新并关闭输出文件",rc);ok=false;}}avformat_free_context(mux);}ring.drainQueue();graph.shutdown();source.close();ring.shutdown();ctx.shutdown();if(ok){progress(.999,L"正在保存正式文件");+ // Bounded deterministic acceptance hook around the real final rename.+ // Normal runs do not wait here; no output or success result is faked.+ wchar_t delayText[16]{};+ if(GetEnvironmentVariableW(L"VEYRA_TEST_EXPORT_SAVE_DELAY_MS",delayText,16)){+ const auto deadline=GetTickCount64()+std::clamp(_wtoi(delayText),0,2000);+ while(!cancel&&GetTickCount64()<deadline)Sleep(5);+ }ok=!cancel&&MoveFileExW(partial.c_str(),output.c_str(),MOVEFILE_WRITE_THROUGH)!=FALSE;if(!ok&&!cancel){const DWORD error=GetLastError();failureReason=std::format(L"视频已编码,但保存文件名失败(Windows错误 {});可保留partial文件",error);veyra::log::error("export-rename",std::format("MoveFileExW failed error={} partial={}",error,utf8(partial)));}if(ok)veyra::log::info("export","encoder drained, mux closed, output saved; no post-export decoding");@@ -287,7 +281,9 @@ bool exportVideo(const std::wstring& input,const std::wstring& output,PlayerOptielse {std::wstring message=cancel?L"导出已取消":failureReason.empty()?L"视频导出失败,请查看诊断":failureReason;std::error_code ec;- message+=std::filesystem::exists(partial,ec)?L";partial文件已保留":L";未生成输出文件";+ std::wstring cleanup;+ if(cancel&&!removeExportTemporaryFile(partial,cleanup))message+=L";"+cleanup;+ else if(std::filesystem::exists(partial,ec))message+=L";临时文件已保留:"+partial;progress(0,message);}return ok;diff --git a/src/ui/QmlExportQueueModel.cpp b/src/ui/QmlExportQueueModel.cppnew file mode 100644index 00000000..03c2fcfa--- /dev/null+++ b/src/ui/QmlExportQueueModel.cpp@@ -0,0 +1,59 @@+#include "veyra/ui/QmlExportQueueModel.h"+#include <QFileInfo>++namespace veyra::ui {+QmlExportQueueModel::QmlExportQueueModel(engine::ExportJobManager& worker,QObject* parent):QAbstractListModel(parent),queue_(worker){}+int QmlExportQueueModel::rowCount(const QModelIndex& parent)const{return parent.isValid()?0:int(queue_.items().size());}+QHash<int,QByteArray> QmlExportQueueModel::roleNames()const{return {{ItemId,"itemId"},{Name,"name"},{Input,"input"},{Output,"output"},{State,"state"},{Progress,"progress"},{Note,"note"},{Duration,"duration"},{Current,"current"},{Locked,"locked"},{Inspecting,"inspecting"}};}+QVariant QmlExportQueueModel::data(const QModelIndex& index,int role)const{+ if(!index.isValid()||index.row()<0||index.row()>=rowCount())return {};+ const auto& item=queue_.items()[index.row()];+ using S=engine::ExportItemState;+ switch(role){+ case ItemId:return QVariant::fromValue(qulonglong(item.id));+ case Name:return QFileInfo(QString::fromStdWString(item.input)).fileName();+ case Input:return QString::fromStdWString(item.input);+ case Output:return QString::fromStdWString(item.output);+ case State:switch(item.state){case S::Ready:return "ready";case S::Queued:return "queued";case S::Running:return "running";case S::Done:return "done";case S::Failed:return "failed";case S::Cancelled:return "cancelled";}break;+ case Progress:return item.progress;+ case Note:return QString::fromStdWString(item.note);+ case Duration:return item.info.duration;+ case Current:return item.id==selected_;+ case Locked:return item.state==S::Running;+ case Inspecting:return item.inspected!=item.revision;+ }+ return {};+}+QVariantMap QmlExportQueueModel::get(int row)const{+ QVariantMap result;if(row<0||row>=rowCount())return result;+ const auto roles=roleNames();for(auto it=roles.cbegin();it!=roles.cend();++it)result[QString::fromUtf8(it.value())]=data(index(row),it.key());return result;+}+void QmlExportQueueModel::refresh(){if(rowCount())emit dataChanged(index(0),index(rowCount()-1));emit changed();}+void QmlExportQueueModel::setSelectedId(qulonglong id){if(selected_==id||(id&&!queue_.find(id)))return;selected_=id;refresh();}+qulonglong QmlExportQueueModel::addFile(const QString& path,const QString& output){+ beginInsertRows({},rowCount(),rowCount());const auto id=queue_.add(path.toStdWString(),output.toStdWString());endInsertRows();emit changed();return id;+}+bool QmlExportQueueModel::removeItem(qulonglong id){+ for(int row=0;row<rowCount();++row)if(queue_.items()[row].id==id){+ if(queue_.items()[row].state==engine::ExportItemState::Running)return false;+ beginRemoveRows({},row,row);queue_.remove(id);endRemoveRows();if(selected_==id)selected_=0;emit changed();return true;+ }+ return false;+}+bool QmlExportQueueModel::moveItem(qulonglong id,int destination){+ if(destination<0||destination>=rowCount())return false;+ for(int row=0;row<rowCount();++row)if(queue_.items()[row].id==id){+ if(row==destination)return true;if(queue_.items()[row].state==engine::ExportItemState::Running)return false;+ if(!beginMoveRows({},row,row,{},destination>row?destination+1:destination))return false;+ const bool result=queue_.move(id,destination);endMoveRows();emit changed();return result;+ }+ return false;+}+bool QmlExportQueueModel::retryItem(qulonglong id){const bool result=queue_.retry(id);if(result)refresh();return result;}+void QmlExportQueueModel::clearWaiting(){+ using S=engine::ExportItemState;+ const bool busy=queue_.busy();+ for(int i=rowCount()-1;i>=0;--i){const auto& item=queue_.items()[i];if(!busy||item.state==S::Ready||item.state==S::Queued||item.state==S::Cancelled)removeItem(item.id);}+}+bool QmlExportQueueModel::tick(){const bool changed=queue_.tick();if(changed)refresh();return changed;}+}diff --git a/src/ui/QmlPlayerBridge.cpp b/src/ui/QmlPlayerBridge.cppindex fe5e9be2..3d13829c 100644--- a/src/ui/QmlPlayerBridge.cpp+++ b/src/ui/QmlPlayerBridge.cpp@@ -1,4 +1,5 @@#include "veyra/ui/QmlPlayerBridge.h"+#include "veyra/ui/QmlExportQueueModel.h"#include <QRegion>#include <QWindow>@@ -22,6 +23,7 @@#include <QTimer>#include <QBuffer>#include <QImage>+#include <QImageReader>#include <algorithm>#include <cmath>@@ -96,6 +98,15 @@ QString mmss(double seconds) {return h > 0 ? QStringLiteral("%1:%2:%3").arg(h).arg(m, 2, 10, QLatin1Char('0')).arg(s, 2, 10, QLatin1Char('0')): QStringLiteral("%1:%2").arg(m).arg(s, 2, 10, QLatin1Char('0'));}+void exportCompletionNotice(bool enabled,uint64_t event,const char* kind){+ const BOOL queued=enabled?MessageBeep(MB_OK):FALSE;+ veyra::log::info("export-notify",std::format("kind={} event={} soundEnabled={} systemSoundQueued={}",kind,event,enabled,queued!=FALSE));+}+bool exportFileClosed(const QString& path){+ HANDLE file=CreateFileW(wideOf(path).c_str(),GENERIC_READ,0,nullptr,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,nullptr);+ if(file==INVALID_HANDLE_VALUE)return false;+ CloseHandle(file);return true;+}} // namespacestruct QmlPlayerBridge::Impl {@@ -176,10 +187,6 @@ struct QmlPlayerBridge::Impl {qint64 colourLastPushMs = 0;int colourLastIndex = -1;bool colourReplaying = false;- // Export queue rows as the UI added them, tracked against the manager's- // snapshot by output path (the manager itself only reports a count).- struct ExportRow { std::wstring input, output; QString state; double progress = 0; QString note; };- std::vector<ExportRow> exportRows;// Poster data URL cache, per session.uint64_t posterSession = 0;QString posterUrl;@@ -200,6 +207,12 @@ struct QmlPlayerBridge::Impl {// The export job manager is the real thing: state, progress and encoded// counts come from its snapshot.engine::ExportJobManager exportJob;+ QmlExportQueueModel exportQueue{exportJob};+ int exportContainer=0;+ uint64_t exportNotifiedBatch=0;+ QString pendingFrameExport;+ qint64 pendingFrameDeadline=0;+ uint64_t imageCompletionEvent=0;engine::ExportJobSnapshot exportSnapshot;bool exportHevc = false;uint32_t exportBitrateMbps = 0;@@ -612,6 +625,7 @@ QmlPlayerBridge::QmlPlayerBridge(engine::EngineController& engine, std::filesystconnect(this,&QmlPlayerBridge::snapshotChanged,this,&QmlPlayerBridge::fgChoicesChanged);connect(this,&QmlPlayerBridge::settingsChanged,this,&QmlPlayerBridge::fgChoicesChanged);impl_->loadPrefs();+ connect(&impl_->exportQueue,&QmlExportQueueModel::changed,this,&QmlPlayerBridge::exportChanged);if (qApp) qApp->installEventFilter(this);// Before anything opens: the renderer reads the output choice at start().applyPreference(QStringLiteral("audioDevice"));@@ -800,7 +814,7 @@ QmlPlayerBridge::QmlPlayerBridge(engine::EngineController& engine, std::filesyst}// An export in flight needs its own poll; it is a separate job and its// snapshot is not part of the player snapshot.- if (impl_->exportSnapshot.active() || impl_->exportSnapshot.queued > 0) pollExport();+ if (impl_->exportQueue.queue().needsTick()) pollExport();});impl_->timer->start(16);startGpuSampler();@@ -2443,6 +2457,7 @@ int QmlPlayerBridge::imageBatchTotal() const { return int(impl_->imageFiles.sizeint QmlPlayerBridge::imageBatchFailures() const { return impl_->imageFailures; }QString QmlPlayerBridge::imageBatchStatus() const { return impl_->imageStatus; }void QmlPlayerBridge::saveFrameDialog() {+ if(!impl_->pendingFrameExport.isEmpty()||imageBatchActive()){emit notice(tr("请等待当前图片导出完成"),true);return;}if (!hasSource()) { emit notice(tr("没有可保存的画面"), true); return; }if (impl_->chain.mode == engine::ChainMode::Node) {emit notice(tr("图片导出只接受列表模式;请切回列表模式再导出"), true); return;@@ -2454,6 +2469,7 @@ void QmlPlayerBridge::saveFrameDialog() {if (path.isEmpty()) return;if (QFileInfo::exists(path)) { emit notice(tr("目标文件已存在,请换一个文件名"), true); return; }impl_->engine.saveFrame(wideOf(QDir::toNativeSeparators(path)));+ impl_->pendingFrameExport=path;impl_->pendingFrameDeadline=QDateTime::currentMSecsSinceEpoch()+30000;emit notice(tr("正在保存:%1").arg(QDir::toNativeSeparators(path)), false);}void QmlPlayerBridge::exportImagesDialog() {@@ -2486,6 +2502,16 @@ void QmlPlayerBridge::cancelImageBatch() {}void QmlPlayerBridge::tickImageBatch() {auto& i = *impl_;+ if(!i.pendingFrameExport.isEmpty()){+ QString path=i.pendingFrameExport;+ if(!QFileInfo(path).isFile())path=QFileInfo(path).path()+QLatin1Char('/')+QFileInfo(path).completeBaseName()+QStringLiteral(".jxr");+ const bool reported=i.snapshot.status.find(L"已保存")!=std::wstring::npos;+ if(reported&&QFileInfo(path).size()>0&&exportFileClosed(path)){+ const bool valid=path.endsWith(QStringLiteral(".jxr"),Qt::CaseInsensitive)||!QImageReader(path).read().isNull();+ if(valid){i.pendingFrameExport.clear();exportCompletionNotice(exportCompletionSound(),++i.imageCompletionEvent,"image");emit notice(tr("图片导出完成:%1").arg(path),false);}+ }+ if(!i.pendingFrameExport.isEmpty()&&QDateTime::currentMSecsSinceEpoch()>i.pendingFrameDeadline){i.pendingFrameExport.clear();emit notice(tr("图片保存未确认完成,请查看诊断"),true);}+ }if (i.imagePhase == Impl::ImagePhase::Idle) return;auto fail = [&](const QString& why) {++i.imageFailures;@@ -2502,6 +2528,7 @@ void QmlPlayerBridge::tickImageBatch() {veyra::log::info("image-batch", std::format("finished done={} failed={}", i.imageDone, i.imageFailures));emit imageBatchChanged();emit notice(i.imageStatus, i.imageFailures > 0);+ if(i.imageDone>0&&i.imageFailures==0)exportCompletionNotice(exportCompletionSound(),++i.imageCompletionEvent,"image-batch");return;}const QString input = i.imageFiles[i.imageIndex];@@ -2527,7 +2554,7 @@ void QmlPlayerBridge::tickImageBatch() {// Saving: the engine writes on its own thread; HDR output becomes .jxr.QString written = i.imageTarget;if (!QFileInfo(written).isFile()) written = QFileInfo(i.imageTarget).path() + QLatin1Char('/') + QFileInfo(i.imageTarget).completeBaseName() + QStringLiteral(".jxr");- if (QFileInfo(written).isFile() && QFileInfo(written).size() > 0) {+ if (QFileInfo(written).isFile() && QFileInfo(written).size() > 0 && s.status.find(L"已保存")!=std::wstring::npos && exportFileClosed(written)) {++i.imageDone;veyra::log::info("image-batch", std::format("saved index={} path={}", i.imageIndex, written.toStdString()));i.imagePhase = Impl::ImagePhase::Opening; i.imageSession = 0;@@ -3422,60 +3449,33 @@ QString QmlPlayerBridge::videoHdrStatus() const { return utf8Of(impl_->snapshot.// Poll the export job once per UI tick. Its snapshot is the source of the// numbers below; nothing here keeps a parallel counter that could drift.void QmlPlayerBridge::pollExport() {- const auto failuresBefore = impl_->exportSnapshot.queueFailures;- impl_->exportSnapshot = impl_->exportJob.poll();- const auto& snap = impl_->exportSnapshot;- if (snap.queueFailures > failuresBefore) {- emit notice(tr("队列中有一项未能开始:%1").arg(utf8Of(snap.lastQueueFailure)), true);- // The manager names no row; the oldest waiting row that is not the- // job now running is the one it refused.- for (auto& row : impl_->exportRows)- if (row.state == QLatin1String("queued") && row.output != snap.output) {- row.state = QStringLiteral("failed"); row.note = utf8Of(snap.lastQueueFailure); break;- }+ const auto& queue=impl_->exportQueue.queue();+ const bool changed=impl_->exportQueue.tick();+ impl_->exportSnapshot=queue.snapshot();+ const auto event=queue.successEvent();+ if(event&&event!=impl_->exportNotifiedBatch){+ impl_->exportNotifiedBatch=event;+ exportCompletionNotice(exportCompletionSound(),event,"video-batch");+ emit notice(utf8Of(queue.status()),false);}- for (auto& row : impl_->exportRows) {- if (row.output != snap.output || snap.output.empty()) continue;- using S = engine::ExportState;- if (snap.active()) { row.state = snap.state == S::Paused ? QStringLiteral("paused") : QStringLiteral("running"); row.progress = snap.progress; }- else if (snap.state == S::Succeeded) { row.state = QStringLiteral("done"); row.progress = 1.0; }- else if (snap.state == S::Failed) { row.state = QStringLiteral("failed"); row.note = utf8Of(snap.message); }- else if (snap.state == S::Cancelled) row.state = QStringLiteral("cancelled");- }- // A running row that is no longer the job (the next one started) finished.- if (!snap.output.empty())- for (auto& row : impl_->exportRows)- if (row.state == QLatin1String("running") && row.output != snap.output) { row.state = QStringLiteral("done"); row.progress = 1.0; }- emit exportChanged();+ if(changed)emit exportChanged();}-bool QmlPlayerBridge::exportRunning() const { return impl_->exportSnapshot.active(); }+bool QmlPlayerBridge::exportRunning() const { return impl_->exportQueue.queue().busy(); }bool QmlPlayerBridge::exportPaused() const {return impl_->exportSnapshot.state == engine::ExportState::Paused;}double QmlPlayerBridge::exportProgress() const { return impl_->exportSnapshot.progress; }QString QmlPlayerBridge::exportStatus() const {- switch (impl_->exportSnapshot.state) {- case engine::ExportState::Idle: return tr("未开始");- case engine::ExportState::Preparing: return tr("准备中…");- case engine::ExportState::Running: return tr("导出中…");- case engine::ExportState::Paused: return tr("已暂停");- case engine::ExportState::Finishing: return tr("收尾中…");- case engine::ExportState::Succeeded: return tr("已完成");- case engine::ExportState::Failed: return tr("失败");- case engine::ExportState::Cancelled: return tr("已取消");- }- return {};-}-QString QmlPlayerBridge::exportTarget() const {- const auto& out = impl_->exportSnapshot.output;- return out.empty() ? utf8Of(impl_->exportOutput) : utf8Of(out);+ if(impl_->exportSnapshot.active())return utf8Of(impl_->exportSnapshot.message);+ return utf8Of(impl_->exportQueue.queue().status());}+QString QmlPlayerBridge::exportTarget() const { return utf8Of(impl_->exportOutput); }int QmlPlayerBridge::exportEncoded() const { return int(impl_->exportSnapshot.encoded); }int QmlPlayerBridge::exportGenerated() const { return int(impl_->exportSnapshot.generated); }double QmlPlayerBridge::exportEtaSeconds() const { return impl_->exportSnapshot.etaSeconds; }-int QmlPlayerBridge::exportQueueCount() const { return int(impl_->exportSnapshot.queued); }-int QmlPlayerBridge::exportQueueFailures() const { return int(impl_->exportSnapshot.queueFailures); }+int QmlPlayerBridge::exportQueueCount() const { return int(std::count_if(impl_->exportQueue.queue().items().begin(),impl_->exportQueue.queue().items().end(),[](const auto& i){return i.state==engine::ExportItemState::Queued;})); }+int QmlPlayerBridge::exportQueueFailures() const { return int(impl_->exportQueue.queue().failures()); }QString QmlPlayerBridge::exportQueueFailure() const { return utf8Of(impl_->exportSnapshot.lastQueueFailure); }// HEVC or H.264: the engine's export entry takes this as a flag, so it is a real@@ -3527,6 +3527,8 @@ void QmlPlayerBridge::setExportTrimStart(double seconds) {const double maxStart = end > 0.05 ? end - 0.05 : 0.0;const double value = std::clamp(seconds, 0.0, std::max(0.0, maxStart));if (std::abs(impl_->exportTrimStartSeconds - value) < 0.0005) return;+ const auto selected=impl_->exportQueue.selectedId();+ if(selected&&!impl_->exportQueue.queue().setTrim(selected,value,impl_->exportTrimEndSeconds))return;impl_->exportTrimStartSeconds = value;emit exportChanged();}@@ -3540,6 +3542,8 @@ void QmlPlayerBridge::setExportTrimEnd(double seconds) {const double start = impl_->exportTrimStartSeconds;if (value > 0.0 && value <= start + 0.05) return;if (std::abs(impl_->exportTrimEndSeconds - value) < 0.0005) return;+ const auto selected=impl_->exportQueue.selectedId();+ if(selected&&!impl_->exportQueue.queue().setTrim(selected,impl_->exportTrimStartSeconds,value))return;impl_->exportTrimEndSeconds = value;emit exportChanged();}@@ -3650,6 +3654,7 @@ int QmlPlayerBridge::thumbnailGeneration() const { return impl_->thumbnailGeneravoid QmlPlayerBridge::openPath(const QString& path) {if (path.isEmpty()) return;+ impl_->exportQueue.setSelectedId(0);++impl_->liveOpenGen; impl_->pendingLiveText.clear(); // a waiting live open is droppedimpl_->exportTrimStartSeconds = 0.0;impl_->exportTrimEndSeconds = 0.0;@@ -3994,8 +3999,7 @@ void QmlPlayerBridge::chooseExportPath() {emit notice(tr("节点链尚未接入导出执行器,请切换列表模式后导出"), true);return;}- const QString path = QFileDialog::getSaveFileName(nullptr, tr("导出到"), QString(),- tr("MP4 视频 (*.mp4);;所有文件 (*)"));+ const QString path = QFileDialog::getExistingDirectory(nullptr,tr("选择导出目录"),exportTarget());setExportPath(path);}@@ -4007,34 +4011,28 @@ void QmlPlayerBridge::setExportPath(const QString& path) {}void QmlPlayerBridge::startExport() {- QString error;- auto settings = impl_->exportSettings(error);- if (!settings) { emit notice(error, true); return; }- if (impl_->exportOutput.empty()) { emit notice(tr("先选择导出位置"), true); return; }- if (!QFileInfo(utf8Of(impl_->sourceLabel)).isFile()) {- emit notice(tr("先打开要导出的本地文件"), true); return;- }- veyra::log::info("qml-export", std::format("preset={} revision={} nr={} sr={} fg={} bitrate={} srTarget={}",- impl_->exportPresetName.empty() ? "current" : utf8Of(impl_->exportPresetName).toStdString(),- settings->revision, settings->nr, settings->sr, settings->multiplier,- settings->exportBitrateMbps, settings->sr ? int(settings->srTarget) : -1));- const bool started = impl_->exportJob.start(impl_->sourceLabel, impl_->exportOutput,- *settings, impl_->exportHevc, 0,- impl_->snapshot.selectedAudioTrack,- impl_->exportTrimStartSeconds,- impl_->exportTrimEndSeconds,- impl_->exportRateControl);- if (!started) { emit notice(tr("导出启动失败;详见诊断"), true); return; }- impl_->exportRows.push_back({impl_->sourceLabel, impl_->exportOutput, QStringLiteral("running"), 0.0, {}});- pollExport();- emit navigate(QStringLiteral("exp"));+ QString error;auto settings=impl_->exportSettings(error);+ if(!settings){emit notice(error,true);return;}+ if(impl_->exportQueue.count()==0){+ if(!QFileInfo(utf8Of(impl_->sourceLabel)).isFile()){emit notice(tr("请先添加要导出的文件"),true);return;}+ const QString target=exportTarget();+ const bool fileTarget=!target.isEmpty()&&!QFileInfo(target).isDir();+ const auto id=impl_->exportQueue.addFile(utf8Of(impl_->sourceLabel),fileTarget?target:QString());+ impl_->exportQueue.queue().setTrim(id,impl_->exportTrimStartSeconds,impl_->exportTrimEndSeconds);+ impl_->exportQueue.setSelectedId(id);+ }+ if(impl_->exportOutput.empty())chooseExportPath();+ if(impl_->exportOutput.empty())return;+ const QFileInfo target(exportTarget());+ const QString folder=target.isDir()?target.absoluteFilePath():target.absolutePath();+ std::wstring reason;+ if(!impl_->exportQueue.queue().start(wideOf(folder),*settings,impl_->exportHevc,impl_->exportRateControl,reason)){+ emit notice(utf8Of(reason),true);emit exportChanged();return;+ }+ impl_->exportQueue.refresh();pollExport();emit navigate(QStringLiteral("exp"));}-void QmlPlayerBridge::cancelExport() {- impl_->exportJob.cancel();- for (auto& row : impl_->exportRows)- if (row.state == QLatin1String("queued")) row.state = QStringLiteral("cancelled");- pollExport();+ impl_->exportQueue.queue().cancel();impl_->exportQueue.refresh();pollExport();emit exportChanged();}void QmlPlayerBridge::quit() {@@ -4518,38 +4516,20 @@ bool QmlPlayerBridge::applyPresetIndex(int index) {return true;}-void QmlPlayerBridge::enqueueExportFile(const QString& input, const QString& output) {- QString error;- auto settings = impl_->exportSettings(error);- if (!settings) { emit notice(error, true); return; }- if (input.isEmpty() || output.isEmpty()) { emit notice(tr("队列项目缺少输入或输出"), true); return; }- if (!QFileInfo(input).isFile()) { emit notice(tr("队列输入文件不存在"), true); return; }- const bool currentFile = wideOf(input) == impl_->sourceLabel;- const bool busy = impl_->exportJob.poll().active() || impl_->exportJob.queuedCount() > 0;- const bool queued = impl_->exportJob.enqueue(wideOf(input), wideOf(output), *settings, impl_->exportHevc, 0,- currentFile ? impl_->snapshot.selectedAudioTrack : -1,- currentFile ? impl_->exportTrimStartSeconds : 0.0,- currentFile ? impl_->exportTrimEndSeconds : 0.0,- impl_->exportRateControl);- if (!queued) { emit notice(tr("加入导出队列失败;详见诊断"), true); return; }- impl_->exportRows.push_back({wideOf(input), wideOf(output), busy ? QStringLiteral("queued") : QStringLiteral("running"), 0.0, {}});- pollExport();+void QmlPlayerBridge::enqueueExportFile(const QString& input,const QString& output) {+ if(!QFileInfo(input).isFile()){emit notice(tr("队列输入文件不存在"),true);return;}+ impl_->exportQueue.addFile(input,output);emit exportChanged();}--void QmlPlayerBridge::addExportFilesDialog() {- if (impl_->chain.mode == engine::ChainMode::Node) {- emit notice(tr("节点链尚未接入导出执行器,请切换列表模式后导出"), true);- return;- }- const auto files = QFileDialog::getOpenFileNames(nullptr, tr("加入导出队列"), QString(),- tr("媒体文件 (*.mp4 *.mkv *.mov *.avi *.webm *.ts *.m2ts);;所有文件 (*)"));- if (files.isEmpty()) return;- const QString folder = QFileDialog::getExistingDirectory(nullptr, tr("选择队列输出目录"));- if (folder.isEmpty()) return;- for (const auto& file : files) {- const QFileInfo info(file);- enqueueExportFile(file, QDir(folder).filePath(info.completeBaseName() + QStringLiteral(".mp4")));+void QmlPlayerBridge::addExportFiles(const QStringList& paths) {+ for(const auto& path:paths){const auto url=QUrl(path);const QString file=url.isLocalFile()?url.toLocalFile():path;+ if(QFileInfo(file).isFile())impl_->exportQueue.addFile(file);+ else emit notice(tr("无法添加文件:%1").arg(file),true);}+ emit exportChanged();+}+void QmlPlayerBridge::addExportFilesDialog() {+ addExportFiles(QFileDialog::getOpenFileNames(nullptr,tr("加入导出队列"),QString(),+ tr("视频文件 (*.mp4 *.mkv *.mov *.avi *.webm *.ts *.m2ts);;所有文件 (*)")));}bool QmlPlayerBridge::selectExportPreset(int index) {if (index == -1) {@@ -5327,20 +5307,82 @@ bool QmlPlayerBridge::colourPaste() {}QVariantList QmlPlayerBridge::exportItems() const {- QVariantList out;- for (const auto& row : impl_->exportRows) {- const QString input = utf8Of(row.input);- out << QVariantMap{{"name", QFileInfo(input).fileName()}, {"input", input}, {"output", utf8Of(row.output)},- {"state", row.state}, {"progress", row.progress}, {"note", row.note},- {"current", row.input == impl_->sourceLabel}};+ QVariantList result;for(int i=0;i<impl_->exportQueue.count();++i)result<<impl_->exportQueue.get(i);return result;+}+void QmlPlayerBridge::addCurrentExportFile(){+ if(!QFileInfo(utf8Of(impl_->sourceLabel)).isFile())return;+ const auto id=impl_->exportQueue.addFile(utf8Of(impl_->sourceLabel));+ impl_->exportQueue.queue().setTrim(id,impl_->exportTrimStartSeconds,impl_->exportTrimEndSeconds);+ impl_->exportQueue.setSelectedId(id);emit exportChanged();+}+QObject* QmlPlayerBridge::exportQueueModel() const{return &impl_->exportQueue;}+int QmlPlayerBridge::exportContainer()const{return impl_->exportContainer;}+void QmlPlayerBridge::setExportContainer(int value){+ if(value<0||value>1||value==impl_->exportContainer)return;+ impl_->exportContainer=value;impl_->exportQueue.queue().setContainer(static_cast<engine::ExportContainer>(value));+ impl_->exportQueue.refresh();+}+int QmlPlayerBridge::exportReadyCount()const{return int(impl_->exportQueue.queue().readyCount());}+bool QmlPlayerBridge::exportSelectionEditable()const{+ const auto* item=impl_->exportQueue.queue().find(impl_->exportQueue.selectedId());+ return item&&item->state!=engine::ExportItemState::Running&&item->state!=engine::ExportItemState::Queued;+}+int QmlPlayerBridge::exportAudioPolicy()const{+ const auto* item=impl_->exportQueue.queue().find(impl_->exportQueue.selectedId());return item?int(item->media.audio.policy):1;+}+int QmlPlayerBridge::exportSubtitlePolicy()const{+ const auto* item=impl_->exportQueue.queue().find(impl_->exportQueue.selectedId());return item?int(item->media.subtitles.policy):1;+}+QVariantList QmlPlayerBridge::exportTracks()const{+ QVariantList result;const auto* item=impl_->exportQueue.queue().find(impl_->exportQueue.selectedId());if(!item)return result;+ for(const auto& track:item->info.tracks){const auto& selection=track.audio?item->media.audio:item->media.subtitles;+ const bool selected=selection.policy==engine::ExportTrackPolicy::All||selection.contains(track.index);+ result<<QVariantMap{{"index",track.index},{"audio",track.audio},{"selected",selected},{"compatible",track.compatible},+ {"label",QStringLiteral("%1 · %2 · %3%4").arg(track.index).arg(utf8Of(track.codec)).arg(utf8Of(track.language)).arg(track.channels?QStringLiteral(" · %1 声道").arg(track.channels):QString())},+ {"title",utf8Of(track.title)},{"action",utf8Of(track.action)}};}- return out;+ return result;+}+void QmlPlayerBridge::setExportTrackPolicy(bool audio,int policy){+ if(policy<1||policy>3)return;+ auto& queue=impl_->exportQueue.queue();const auto id=impl_->exportQueue.selectedId();const auto* item=queue.find(id);if(!item)return;+ engine::ExportTrackSelection selection;selection.policy=static_cast<engine::ExportTrackPolicy>(policy);+ if(selection.policy==engine::ExportTrackPolicy::Selected){+ for(const auto& track:item->info.tracks)if(track.audio==audio){selection.indices[0]=track.index;selection.count=1;break;}+ if(!selection.count){emit notice(tr("该文件没有可选轨道"),true);return;}+ }+ if(queue.setTracks(id,audio,selection))impl_->exportQueue.refresh();+}+void QmlPlayerBridge::toggleExportTrack(bool audio,int index,bool keep){+ auto& queue=impl_->exportQueue.queue();const auto id=impl_->exportQueue.selectedId();const auto* item=queue.find(id);if(!item)return;+ const auto& previous=audio?item->media.audio:item->media.subtitles;+ engine::ExportTrackSelection selection;selection.policy=engine::ExportTrackPolicy::Selected;+ for(const auto& track:item->info.tracks)if(track.audio==audio){+ // Leaving "all" keeps what "all" actually carried: tracks it skipped for+ // this container stay out instead of turning into a hard failure.+ const bool selected=track.index==index?keep:previous.policy==engine::ExportTrackPolicy::All?track.compatible:previous.contains(track.index);+ if(selected){if(selection.count>=selection.indices.size()){emit notice(tr("手动选择最多 64 条;保留全部不限制轨道数量"),true);return;}selection.indices[selection.count++]=track.index;}+ }+ if(!selection.count)selection.policy=engine::ExportTrackPolicy::None;+ if(queue.setTracks(id,audio,selection))impl_->exportQueue.refresh();+}+void QmlPlayerBridge::previewExportItem(qulonglong id){+ const auto* item=impl_->exportQueue.queue().find(id);if(!item)return;+ const QString input=utf8Of(item->input);const double start=item->start,end=item->end;+ if(input!=utf8Of(impl_->sourceLabel))openPath(input);+ impl_->exportQueue.setSelectedId(id);impl_->exportTrimStartSeconds=start;impl_->exportTrimEndSeconds=end;+ emit exportChanged();+}+bool QmlPlayerBridge::exportCompletionSound()const{return impl_->prefs.value(QStringLiteral("exportCompletionSound"),true).toBool();}+void QmlPlayerBridge::setExportCompletionSound(bool enabled){+ const auto previous=impl_->prefs;impl_->prefs[QStringLiteral("exportCompletionSound")]=enabled;+ if(!impl_->savePrefs()){impl_->prefs=previous;emit notice(tr("提示音设置保存失败"),true);}+ emit exportChanged();}void QmlPlayerBridge::clearFinishedExportItems() {- std::erase_if(impl_->exportRows, [](const auto& row) {- return row.state != QLatin1String("running") && row.state != QLatin1String("queued") &&- row.state != QLatin1String("paused");- });+ for(int row=impl_->exportQueue.count()-1;row>=0;--row){const auto& item=impl_->exportQueue.queue().items()[row];+ if(item.state==engine::ExportItemState::Done||item.state==engine::ExportItemState::Failed||item.state==engine::ExportItemState::Cancelled)impl_->exportQueue.removeItem(item.id);+ }emit exportChanged();}// A thumbnail of any file (export queue rows), through the same provider.diff --git a/tests/integration/ExportWorkflowTests.cpp b/tests/integration/ExportWorkflowTests.cppnew file mode 100644index 00000000..308919bb--- /dev/null+++ b/tests/integration/ExportWorkflowTests.cpp@@ -0,0 +1,142 @@+#include "veyra/engine/ExportJobManager.h"+#include "veyra/engine/ExportQueue.h"+#include <chrono>+#include <filesystem>+#include <fstream>+#include <iostream>+#include <thread>++using namespace veyra::engine;+namespace {+void require(bool value,const char* message){if(!value)throw std::runtime_error(message);}+ExportJobSnapshot finish(ExportJobManager& manager){+ const auto limit=GetTickCount64()+90000;+ ExportJobSnapshot s;+ do{s=manager.poll();if(!s.active())return s;Sleep(10);}while(GetTickCount64()<limit);+ throw std::runtime_error("export exceeded 90 second deadline");+}+void collected(const ExportJobSnapshot& s){+ HANDLE process=OpenProcess(SYNCHRONIZE,FALSE,s.workerPid);+ if(process){const auto state=WaitForSingleObject(process,0);CloseHandle(process);require(state==WAIT_OBJECT_0,"terminal published before process exit");}+}+}+int wmain(int argc,wchar_t** argv){+ const HRESULT com=CoInitializeEx(nullptr,COINIT_MULTITHREADED);+ if(argc==3&&std::wstring_view(argv[1])==L"--export-worker"){+ const int result=runExportWorker(reinterpret_cast<HANDLE>(_wcstoui64(argv[2],nullptr,10)));+ if(SUCCEEDED(com))CoUninitialize();return result;+ }+ if(argc<4)return 2;+ bool passed=false;+ try{+ const std::wstring mode=argv[1],input=argv[2],output=argv[3];+ ExportJobManager manager;EnhancementSettings settings;settings.nr=settings.sr=false;settings.multiplier=1;+ ExportMediaOptions media;+ media.container=mode.find(L"mkv")!=std::wstring::npos?ExportContainer::Matroska:ExportContainer::Mp4;+ media.audio.policy=ExportTrackPolicy::All;media.subtitles.policy=ExportTrackPolicy::All;+ const bool hevc=mode.find(L"hevc")!=std::wstring::npos;+ if(mode==L"queue"){+ std::filesystem::create_directories(output);+ ExportQueue queue(manager);+ const auto a=queue.add(input),b=queue.add(input),c=queue.add(input);+ require(queue.move(c,0),"queue reorder refused");+ require(!queue.busy()&&manager.poll().workerPid==0,"adding implicitly exported");+ std::wstring error;require(queue.start(output,settings,false,veyra::sink::ExportRateControl::Cq,error),"batch refused");+ const auto late=queue.add(input);+ std::vector<uint64_t> order;+ uint64_t job=0;+ const auto deadline=GetTickCount64()+90000;+ while(queue.needsTick()&&GetTickCount64()<deadline){+ queue.tick();const auto s=queue.snapshot();+ if(s.jobId&&s.jobId!=job){job=s.jobId;for(const auto& item:queue.items())if(item.job==job){order.push_back(item.id);require(!queue.remove(item.id),"active row removed");break;}}+ Sleep(10);+ }+ require(!queue.busy(),"batch did not finish");+ require(order==std::vector<uint64_t>{c,a,b},"actual worker launch order differs from reordered model");+ require(queue.find(late)->state==ExportItemState::Ready,"late item joined frozen batch");+ require(queue.successes()==3&&queue.failures()==0&&queue.successEvent()==1,"whole-batch success event wrong");+ for(int i=0;i<10;++i)queue.tick();require(queue.successEvent()==1,"duplicate completion event");+ const auto missing=queue.add(input+L".missing");+ require(queue.start(output,settings,false,veyra::sink::ExportRateControl::Cq,error),"mixed batch refused");+ while(queue.needsTick()&&GetTickCount64()<deadline){queue.tick();Sleep(10);}+ require(queue.find(missing)->state==ExportItemState::Failed,"missing file not reported");+ require(queue.successes()==1&&queue.failures()==1&&queue.successEvent()==1,"mixed batch emitted successful batch event");+ std::wcout<<L"PASS actual order C/A/B, late membership, stable job IDs, mixed failure, completion de-duplication\n";+ }else if(mode==L"lifecycle"){+ // A pre-existing user/legacy partial must survive every cancellation.+ {std::ofstream legacy(std::filesystem::path(output+L".partial"));legacy<<"protected legacy partial";}+ SetEnvironmentVariableW(L"VEYRA_TEST_EXPORT_EXIT_DELAY_MS",L"1200");+ uint64_t lastJob=0;+ for(int round=0;round<3;++round){+ require(manager.start(input,output,settings,false,0),"start after cancel refused");+ auto initial=manager.poll();require(initial.jobId!=lastJob,"retry reused job id");lastJob=initial.jobId;+ if(round>0){+ manager.watching(true);if(round==1)manager.pause(true);+ const auto deadline=GetTickCount64()+20000;+ while(GetTickCount64()<deadline){auto s=manager.poll();require(s.active(),"export finished before requested cancel phase");if(round==1?s.state==ExportState::Paused:s.sourceFrames>=5)break;Sleep(10);}+ }+ const auto requested=GetTickCount64();manager.cancel();+ require(manager.poll().active(),"cancel skipped resource collection state");+ require(!manager.start(input,output,settings,false),"second worker launched while cancelling");+ auto s=finish(manager);collected(s);+ require(s.state==ExportState::Cancelled,"cancel outcome incorrect");+ require(GetTickCount64()-requested>=1000,"delayed worker result stopped polling early");+ require(!std::filesystem::exists(s.temporaryPath),"owned partial leaked on cancel");+ require(!std::filesystem::exists(output),"cancel created final file");+ require(std::filesystem::file_size(output+L".partial")==24,"foreign partial changed");+ std::wcout<<L"cancel round="<<round<<L" job="<<s.jobId<<L" collected=true\n";+ }+ require(manager.start(input,output,settings,false,20),"same output retry failed");+ auto s=finish(manager);collected(s);require(s.state==ExportState::Succeeded,"final retry did not succeed");+ require(s.encoded==20&&std::filesystem::exists(output),"final output incomplete");+ require(!manager.start(input,output,settings,false),"existing output overwritten");+ require(manager.poll().message.find(L"已存在")!=std::wstring::npos,"startup reason was hidden");+ }else if(mode==L"lifecycle-boundary"){+ SetEnvironmentVariableW(L"VEYRA_TEST_EXPORT_SAVE_DELAY_MS",L"1500");+ require(manager.start(input,output,settings,false,2),"save-boundary start refused");+ const auto deadline=GetTickCount64()+15000;+ ExportJobSnapshot s;+ do{s=manager.poll();require(s.active(),"missed final-save boundary");if(s.progress>=.999)break;Sleep(5);}while(GetTickCount64()<deadline);+ require(s.progress>=.999,"final-save boundary never reached");manager.cancel();s=finish(manager);collected(s);+ require(s.state==ExportState::Cancelled&&!std::filesystem::exists(output)&&!std::filesystem::exists(s.temporaryPath),"final-save cancel left final/temporary output");+ SetEnvironmentVariableW(L"VEYRA_TEST_EXPORT_SAVE_DELAY_MS",nullptr);+ require(manager.start(input,output,settings,false,2),"cleanup-failure start refused");+ const auto owned=manager.poll().temporaryPath;+ HANDLE lock=CreateFileW(owned.c_str(),GENERIC_READ,FILE_SHARE_READ|FILE_SHARE_WRITE,nullptr,OPEN_EXISTING,0,nullptr);+ require(lock!=INVALID_HANDLE_VALUE,"could not hold deletion-denying handle");+ manager.cancel();s=finish(manager);collected(s);CloseHandle(lock);+ require(s.state==ExportState::Cancelled&&std::filesystem::exists(owned)&&s.message.find(owned)!=std::wstring::npos,"cleanup failure hid owned file location");+ SetEnvironmentVariableW(L"VEYRA_TEST_EXPORT_EXIT_DELAY_MS",L"1200");+ require(manager.start(input,output,settings,false,2),"old undeletable partial blocked retry");+ const auto successDeadline=GetTickCount64()+15000;+ do{s=manager.poll();if(s.active()&&std::filesystem::exists(output))break;Sleep(5);}while(GetTickCount64()<successDeadline);+ require(s.active()&&s.progress>=.999&&std::filesystem::exists(output),"could not observe saved output before process exit");+ manager.cancel();s=finish(manager);collected(s);+ require(s.state==ExportState::Succeeded&&std::filesystem::exists(output),"late cancel invalidated safely saved success");+ std::wstring reason;require(removeExportTemporaryFile(owned,reason),"released owned partial cleanup failed");+ std::wcout<<L"PASS final-save cancellation, explicit cleanup failure, retry with old partial, late-success cancel race\n";+ }else{+ const double from=mode.find(L"trim")!=std::wstring::npos?0.7:0;+ const double to=from>0?1.7:0;+ if(mode.find(L"none")!=std::wstring::npos)media.audio.policy=media.subtitles.policy=ExportTrackPolicy::None;+ if(mode.find(L"selected")!=std::wstring::npos){media.audio.policy=media.subtitles.policy=ExportTrackPolicy::Selected;media.audio.count=media.subtitles.count=1;media.audio.indices[0]=2;media.subtitles.indices[0]=4;}+ // "reject": the user picked every subtitle track by hand, so a track+ // the container cannot hold must fail the export. "skip": the default+ // "all tracks" policy leaves it out and says so in the result.+ if(mode.find(L"reject")!=std::wstring::npos){+ std::atomic<bool> stop{false};const auto info=ExportStreams::probe(input,ExportMediaOptions{},0,0,stop);+ media.subtitles.policy=ExportTrackPolicy::Selected;media.subtitles.count=0;+ for(const auto& t:info.tracks)if(t.subtitle&&media.subtitles.count<media.subtitles.indices.size())media.subtitles.indices[media.subtitles.count++]=t.index;+ require(media.subtitles.count>0,"reject source has no subtitle track");+ }+ require(manager.start(input,output,settings,hevc,0,-1,from,to,veyra::sink::ExportRateControl::Cq,media),"start refused");+ auto s=finish(manager);collected(s);+ std::wcout<<L"state="<<int(s.state)<<L" encoded="<<s.encoded<<L" message="<<s.message<<L"\n";+ if(mode.find(L"reject")!=std::wstring::npos){require(s.state==ExportState::Failed,"incompatible source was not rejected");require(!std::filesystem::exists(output),"rejection produced final file");require(!s.message.empty(),"failure reason missing");}+ else require(s.state==ExportState::Succeeded,"export failed");+ if(mode.find(L"skip")!=std::wstring::npos)require(s.message.find(L"未保留")!=std::wstring::npos,"skipped tracks not reported");+ }+ passed=true;+ }catch(const std::exception& e){std::cerr<<"FAILED: "<<e.what()<<'\n';}+ if(SUCCEEDED(com))CoUninitialize();return passed?0:1;+}diff --git a/tests/qml/QuickSmokeTests.cpp b/tests/qml/QuickSmokeTests.cppindex e5c478a8..9a433439 100644--- a/tests/qml/QuickSmokeTests.cpp+++ b/tests/qml/QuickSmokeTests.cpp@@ -5,6 +5,7 @@#include <QDir>#include <QFileInfo>#include <QQmlEngine>+#include <QQmlContext>#include <QtQml/qqml.h>#include <QtQuickTest/quicktest.h>@@ -12,11 +13,14 @@ class Setup : public QObject {Q_OBJECTpublic slots:void qmlEngineAvailable(QQmlEngine* engine) {+ engine->rootContext()->setContextProperty(QStringLiteral("exportTestOutputDirectory"),qEnvironmentVariable("VEYRA_EXPORT_TEST_ARTIFACTS"));engine->addImportPath(QDir(QCoreApplication::applicationDirPath()).filePath(QStringLiteral("qml")));// ProPage is private to the production shell's directory, not exported// by Veyra/qmldir. Register it only here to test its real inline controls.qmlRegisterType(QUrl::fromLocalFile(QDir(QCoreApplication::applicationDirPath()).filePath(QStringLiteral("qml/Veyra/ProPage.qml"))), "VeyraTest", 1, 0, "ProPage");+ qmlRegisterType(QUrl::fromLocalFile(QDir(QCoreApplication::applicationDirPath()).filePath(+ QStringLiteral("qml/Veyra/ExportPage.qml"))), "VeyraTest", 1, 0, "ExportPage");}};diff --git a/tests/qml/quick/tst_export.qml b/tests/qml/quick/tst_export.qmlnew file mode 100644index 00000000..36379b3e--- /dev/null+++ b/tests/qml/quick/tst_export.qml@@ -0,0 +1,135 @@+import QtQuick+import QtQuick.Controls+import QtTest+import Veyra+import VeyraTest 1.0++Rectangle {+ id: fixture+ width: 1280; height: 720+ color: Theme.bgOuter+ ListModel {+ id: queue+ property double selectedId: 0+ function moveItem(id, destination) { for(let i=0;i<count;++i)if(get(i).itemId===id){move(i,destination,1);return true} return false }+ function removeItem(id) { for(let i=0;i<count;++i)if(get(i).itemId===id){remove(i);return true}return false }+ function clearWaiting(){clear()}+ function retryItem(id){}+ }+ QtObject {+ id: backend+ property var exportQueueModel: queue+ property bool hasSource: false+ property bool isCapture: false+ property bool exportRunning: false+ property bool exportPaused: false+ property bool exportHevc: false+ property bool exportCompletionSound: true+ property bool exportSelectionEditable: true+ property int exportContainer: 0+ property int exportSrTargetIndex: -1+ property int exportRateControl: 2+ property int exportBitrateMbps: 24+ property int exportReadyCount: queue.count+ property int exportQueueCount: 0+ property int exportEncoded: 0+ property int exportAudioPolicy: 1+ property int exportSubtitlePolicy: 1+ property real exportProgress: 0+ property real exportTrimStart: 0+ property real exportTrimEnd: 0+ property string exportPresetName: "当前播放设置"+ property string exportTarget: "E:/output"+ property string exportStatus: "添加文件后,点击开始导出"+ property var exportTracks: []+ property var presetChoices: [{id: "-1",label: "当前播放设置"}]+ property bool imageBatchActive: false+ property string imageBatchStatus: ""+ property int compareMode: 0+ property real duration: 0+ property real position: 0+ property string positionText: "0:00"+ property string statusText: "选择左侧文件预览"+ property bool running: false+ property bool paused: false+ property int thumbnailGeneration: 0+ property int starts: 0+ property int additions: 0+ function fileThumbnailId(path, seconds){return ""}+ function formatTime(t){return Number(t).toFixed(1)}+ function previewExportItem(id){queue.selectedId=id}+ function addExportFilesDialog(){++additions}+ function addExportFiles(paths){++additions}+ function startExport(){++starts}+ function togglePlayPause(){}+ function setExportTrackPolicy(audio,policy){}+ }+ ExportPage { id: page; property var veyra: backend; pageId: "exp"; visible: true; enabled: true }+ TestCase {+ name: "ExportPage"+ when: windowShown+ function init(){+ fixture.width=1280;fixture.height=720;page.compactTab=0+ fixture.Window.window.width=1280;fixture.Window.window.height=720+ queue.clear();queue.selectedId=0;backend.starts=0;backend.additions=0+ for(let i=0;i<20;++i)queue.append({itemId:i+1,name:"clip-"+i+".mkv",input:"clip-"+i,output:"",state:"ready",note:"",duration:120,progress:0,current:false,locked:false,inspecting:false})+ waitForPolish(fixture.Window.window)+ }+ function inside(item, outer){+ const p=item.mapToItem(outer,0,0)+ verify(p.x>=-0.5&&p.y>=-0.5,item.objectName+" starts outside")+ verify(p.x+item.width<=outer.width+0.5&&p.y+item.height<=outer.height+0.5,item.objectName+" ends outside "+p.x+","+p.y+" "+item.width+","+item.height)+ }+ function test_layout_data(){return [{tag:"minimum",w:720,h:260},{tag:"720p",w:1280,h:720},{tag:"laptop",w:1366,h:768},{tag:"1080p",w:1920,h:1080}]}+ function test_layout(data){+ fixture.width=data.w;fixture.height=data.h+ fixture.Window.window.width=data.w;fixture.Window.window.height=data.h+ waitForPolish(fixture.Window.window)+ for(let tab=0;tab<3;++tab){+ page.compactTab=tab;waitForPolish(fixture.Window.window)+ for(const name of ["export-queue-card","export-settings-card","export-preview-card","export-trim-card","export-footer"]){const item=findChild(page,name);if(item.visible)inside(item,page)}+ inside(findChild(page,"export-start"),page)+ if(tab===2||!page.compact){+ const select=findChild(page,"export-resolution")+ const scroll=findChild(page,"export-settings-scroll")+ const point=select.mapToItem(scroll,0,0)+ verify(point.x>=0&&point.x+select.width<=scroll.width+1,"resolution must fit horizontally")+ }+ }+ }+ function test_queue_actions(){+ mouseClick(findChild(page,"export-add-files"));compare(backend.additions,1);compare(backend.starts,0)+ const row=findChild(page,"export-queue-row-1");verify(row!==null)+ mouseClick(row,100,20);tryCompare(queue,"selectedId",2)+ mouseClick(findChild(page,"export-remove-0"));compare(queue.count,19);compare(queue.get(0).itemId,2)+ const handle=findChild(page,"export-drag-0")+ mouseDrag(handle,8,20,0,156,Qt.LeftButton,0,200)+ compare(queue.get(2).itemId,2)+ mouseClick(findChild(page,"export-start"));compare(backend.starts,1)+ mouseClick(findChild(page,"export-clear-queue"));compare(queue.count,0)+ }+ function test_resolution_menu_fits_short_window(){+ fixture.width=720;fixture.height=260;page.compactTab=2+ fixture.Window.window.width=720;fixture.Window.window.height=260+ waitForPolish(fixture.Window.window)+ const scroll=findChild(page,"export-settings-scroll")+ const select=findChild(page,"export-resolution")+ scroll.contentItem.contentY=select.mapToItem(scroll.contentItem.contentItem,0,0).y+ waitForPolish(fixture.Window.window)+ mouseClick(select,select.width/2,select.height/2)+ tryCompare(select.popup,"visible",true)+ verify(select.popup.y>=0&&select.popup.y+select.popup.height<=fixture.Window.window.height)+ select.popup.close()+ }+ function cleanupTestCase(){+ if(!exportTestOutputDirectory)return+ fixture.width=1280;fixture.height=720;fixture.Window.window.width=1280;fixture.Window.window.height=720+ page.compactTab=0;waitForPolish(fixture.Window.window);wait(50)+ findChild(page,"export-settings-scroll").contentItem.contentY=0+ grabImage(fixture).save(exportTestOutputDirectory+"/export-1280.png")+ fixture.width=720;fixture.height=260;fixture.Window.window.width=720;fixture.Window.window.height=260+ page.compactTab=2;waitForPolish(fixture.Window.window);wait(50)+ grabImage(fixture).save(exportTestOutputDirectory+"/export-720-settings.png")+ }+ }+}diff --git a/tests/unit/ExportQueueTests.cpp b/tests/unit/ExportQueueTests.cppnew file mode 100644index 00000000..83fefcd4--- /dev/null+++ b/tests/unit/ExportQueueTests.cpp@@ -0,0 +1,34 @@+#include "veyra/engine/ExportQueue.h"+#include <iostream>+#include <stdexcept>+using namespace veyra::engine;+void check(bool ok,const char* why){if(!ok)throw std::runtime_error(why);}+int wmain(int argc,wchar_t** argv){+ if(argc!=2)return 2;+ try{+ ExportJobManager worker;ExportQueue q(worker);+ std::vector<uint64_t> ids;+ for(int i=0;i<20;++i)ids.push_back(q.add(L"missing-test-file.mkv"));+ check(!q.busy()&&q.readyCount()==20&&worker.poll().workerPid==0,"adding launched a worker");+ check(q.move(ids[19],0)&&q.items()[0].id==ids[19],"reorder failed");+ check(q.setTrim(ids[0],1,2)&&q.setTrim(ids[1],3,4),"trim edit failed");+ check(q.find(ids[0])->start==1&&q.find(ids[1])->start==3,"trim leaked between files");+ check(!q.setTrim(ids[0],4,1),"invalid trim accepted");+ ExportTrackSelection selected;selected.policy=ExportTrackPolicy::Selected;selected.count=1;selected.indices[0]=2;+ check(q.setTracks(ids[0],true,selected),"track selection failed");+ check(q.find(ids[1])->media.audio.policy==ExportTrackPolicy::All,"track choice leaked between files");+ q.setContainer(ExportContainer::Matroska);+ EnhancementSettings settings;settings.nr=settings.sr=false;settings.multiplier=1;+ std::wstring error;check(q.start(argv[1],settings,false,veyra::sink::ExportRateControl::Cq,error),"batch setup failed");+ const auto batch=q.batchId();auto extra=q.add(L"next-batch.mp4");+ check(q.find(extra)->batch!=batch,"new item joined active batch");+ check(!q.setTrim(ids[0],0,0),"frozen trim changed");+ check(q.move(ids[1],0)&&q.items()[0].id==ids[1],"waiting reorder failed");+ q.cancel();check(!q.busy()&&q.readyCount()==21&&q.successEvent()==0,"cancel lost pending items or reported success");+ check(q.remove(ids[0])&&q.items().size()==20,"remove failed");+ q.clearWaiting();check(q.items().empty(),"clear failed");+ check(!q.start(argv[1],settings,false,veyra::sink::ExportRateControl::Cq,error),"empty batch accepted");+ std::cout<<"PASS: 20-item queue, stable IDs, ordering, frozen settings, per-file tracks/trim, cancel, clear\n";+ }catch(const std::exception& e){std::cerr<<e.what()<<'\n';return 1;}+ return 0;+}