Bring PS5 GTA6 to 120FPS with DLSS 5. An advanced Windows video player and capture enhancement tool featuring real-time preview for videos, images, and capture card sources. Combine AI-powered Super Resolution, DLSS5 image enhancement, and Frame Generation to deliver a next-generation visual experience.
C++
feat(recording): record the processed picture from the player
Veyra Goal Agent2c80233a8716
diff --git a/CMakeLists.txt b/CMakeLists.txtindex d49711d9..2b6ebc1b 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -1366,7 +1366,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/EngineWatchdog.cpp src/engine/PreviewGpuSession.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)+ add_library(veyra_engine STATIC src/engine/EngineController.cpp src/engine/EngineWatchdog.cpp src/engine/PreviewGpuSession.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 src/engine/LiveRecorder.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/i18n/catalog.json b/i18n/catalog.jsonindex d02f8e3b..cd77ad91 100644--- a/i18n/catalog.json+++ b/i18n/catalog.json@@ -1211,6 +1211,13 @@"en": "HDR sources are shown as SDR too; the same setting as the capture card's \"Show as SDR\"","ja": "HDR ソースも SDR で表示します。キャプチャーカードの「SDR で表示」と同じ設定です"},+ {+ "zh": "HDR 画面固定使用 HEVC 10bit",+ "src": "qml/SettingsPage.qml",+ "zh-TW": "HDR 畫面固定使用 HEVC 10bit",+ "en": "HDR video always uses HEVC 10bit",+ "ja": "HDR 映像は常に HEVC 10bit を使用します"+ },{"zh": "HDR 补帧闪黑兼容","src": "qml/SettingsPage.qml",@@ -3696,6 +3703,13 @@"en": "High","ja": "高め"},+ {+ "zh": "停止录制",+ "src": "qml/ProPage.qml",+ "zh-TW": "停止錄製",+ "en": "Stop recording",+ "ja": "録画を停止"+ },{"zh": "像素格式","src": "qml/DialogHost.qml",@@ -4152,6 +4166,13 @@"en": "Write container index","ja": "コンテナーインデックスの書き込み"},+ {+ "zh": "写入录制帧失败",+ "src": "src/engine/LiveRecorder.cpp",+ "zh-TW": "寫入錄製影格失敗",+ "en": "Writing a recorded frame failed",+ "ja": "録画フレームの書き込みに失敗しました"+ },{"zh": "写入视频帧","src": "src/engine/VideoExportJob.cpp",@@ -7813,6 +7834,13 @@"en": "Starting an export closes what is playing so the whole GPU goes to the export.","ja": "書き出しを開始すると再生中のコンテンツを閉じ、GPU をすべて書き出しに回します。"},+ {+ "zh": "开始录制",+ "src": "src/engine/EngineController.cpp",+ "zh-TW": "開始錄製",+ "en": "Recording started",+ "ja": "録画を開始しました"+ },{"zh": "开始捕获","src": "qml/DialogHost.qml",@@ -8170,6 +8198,20 @@"en": "Active: custom adjustments (no matching preset)","ja": "適用中:カスタム調整(一致するプリセットなし)"},+ {+ "zh": "当前画面尺寸不可用",+ "src": "src/engine/LiveRecorder.cpp",+ "zh-TW": "目前畫面尺寸不可用",+ "en": "The current picture size is unavailable",+ "ja": "現在の画面サイズを利用できません"+ },+ {+ "zh": "当前画面尺寸为奇数,无法录制",+ "src": "src/engine/LiveRecorder.cpp",+ "zh-TW": "目前畫面尺寸為奇數,無法錄製",+ "en": "The current picture size is odd and cannot be recorded",+ "ja": "現在の画面サイズが奇数のため録画できません"+ },{"zh": "当前硬件或包不支持所选效果,请查看组件页","src": "src/ui/QmlPlayerBridge.cpp",@@ -8219,6 +8261,83 @@"en": "Not an NVIDIA adapter: NR, NVIDIA super resolution and DLSS are disabled; XeSS preview and AMD optical flow are available","ja": "NVIDIA 以外のアダプターです:NR、NVIDIA 超解像、DLSS は無効です。XeSS のプレビューと AMD オプティカルフローは使えます"},+ {+ "zh": "录制",+ "src": "qml/ProPage.qml",+ "zh-TW": "錄製",+ "en": "Record",+ "ja": "録画"+ },+ {+ "zh": "录制 %1 秒",+ "src": "qml/ProPage.qml",+ "zh-TW": "錄製 %1 秒",+ "en": "Record in %1 s",+ "ja": "録画 %1 秒後"+ },+ {+ "zh": "录制保存位置",+ "src": "qml/SettingsPage.qml",+ "zh-TW": "錄製儲存位置",+ "en": "Recording folder",+ "ja": "録画の保存先"+ },+ {+ "zh": "录制已在进行中",+ "src": "src/engine/EngineController.cpp",+ "zh-TW": "錄製已在進行中",+ "en": "A recording is already running",+ "ja": "すでに録画中です"+ },+ {+ "zh": "录制已结束",+ "src": "src/engine/EngineController.cpp",+ "zh-TW": "錄製已結束",+ "en": "Recording finished",+ "ja": "録画を終了しました"+ },+ {+ "zh": "录制已结束:%1",+ "src": "src/ui/QmlPlayerBridge.cpp",+ "zh-TW": "錄製已結束:%1",+ "en": "Recording finished: %1",+ "ja": "録画を終了しました:%1"+ },+ {+ "zh": "录制帧率",+ "src": "qml/SettingsPage.qml",+ "zh-TW": "錄製影格率",+ "en": "Recording frame rate",+ "ja": "録画のフレームレート"+ },+ {+ "zh": "录制文件已存在,请更换保存位置",+ "src": "src/engine/LiveRecorder.cpp",+ "zh-TW": "錄製檔案已存在,請更換儲存位置",+ "en": "The recording file already exists; choose another folder",+ "ja": "録画ファイルが既に存在します。保存先を変更してください"+ },+ {+ "zh": "录制目录不存在:%1",+ "src": "src/ui/QmlPlayerBridge.cpp",+ "zh-TW": "錄製資料夾不存在:%1",+ "en": "The recording folder does not exist: %1",+ "ja": "録画フォルダが存在しません:%1"+ },+ {+ "zh": "录制码率",+ "src": "qml/SettingsPage.qml",+ "zh-TW": "錄製位元率",+ "en": "Recording bitrate",+ "ja": "録画のビットレート"+ },+ {+ "zh": "录制编码",+ "src": "qml/SettingsPage.qml",+ "zh-TW": "錄製編碼",+ "en": "Recording codec",+ "ja": "録画のコーデック"+ },{"zh": "往返 ","src": "qml/StreamHud.qml",@@ -9438,6 +9557,13 @@"en": "Could not write the export file","ja": "書き出しファイルに書き込めませんでした"},+ {+ "zh": "无法写入录制文件头",+ "src": "src/engine/LiveRecorder.cpp",+ "zh-TW": "無法寫入錄製檔案標頭",+ "en": "Cannot write the recording file header",+ "ja": "録画ファイルのヘッダーを書き込めません"+ },{"zh": "无法分配媒体上下文","src": "src/media/DemuxSession.cpp",@@ -9473,6 +9599,34 @@"en": "Could not create the export communication resources","ja": "書き出し用の通信リソースを作成できませんでした"},+ {+ "zh": "无法创建录制封装器",+ "src": "src/engine/LiveRecorder.cpp",+ "zh-TW": "無法建立錄製封裝器",+ "en": "Cannot create the recording muxer",+ "ja": "録画の封装器を作成できません"+ },+ {+ "zh": "无法创建录制文件",+ "src": "src/engine/LiveRecorder.cpp",+ "zh-TW": "無法建立錄製檔案",+ "en": "Cannot create the recording file",+ "ja": "録画ファイルを作成できません"+ },+ {+ "zh": "无法创建录制目录:",+ "src": "src/engine/LiveRecorder.cpp",+ "zh-TW": "無法建立錄製資料夾:",+ "en": "Cannot create the recording folder: ",+ "ja": "録画フォルダを作成できません:"+ },+ {+ "zh": "无法创建录制视频流",+ "src": "src/engine/LiveRecorder.cpp",+ "zh-TW": "無法建立錄製影片串流",+ "en": "Cannot create the recording video stream",+ "ja": "録画の映像ストリームを作成できません"+ },{"zh": "无法创建拼接输出","src": "src/engine/VideoExportJob.cpp",@@ -9550,6 +9704,13 @@"en": "Could not start streaming; see the log.","ja": "ストリーミングを開始できませんでした。ログを確認してください。"},+ {+ "zh": "无法开始录制",+ "src": "src/engine/EngineController.cpp",+ "zh-TW": "無法開始錄製",+ "en": "Cannot start recording",+ "ja": "録画を開始できません"+ },{"zh": "无法打开","src": "src/ui/QmlPlayerBridge.cpp",@@ -10593,6 +10754,13 @@"en": "No cap","ja": "上限なし"},+ {+ "zh": "未设置录制保存位置",+ "src": "src/engine/LiveRecorder.cpp",+ "zh-TW": "未設定錄製儲存位置",+ "en": "No recording folder is set",+ "ja": "録画の保存先が設定されていません"+ },{"zh": "未输出","src": "qml/NodePage.qml",@@ -11526,7 +11694,7 @@},{"zh": "没有可用的视频编码器",- "src": "src/engine/VideoExportJob.cpp",+ "src": "src/engine/LiveRecorder.cpp","zh-TW": "沒有可用的影片編碼器","en": "No video encoder available","ja": "使用できる動画エンコーダーがありません"@@ -11545,6 +11713,13 @@"en": "No video data received. Usually the firewall or port forwarding does not allow UDP 47998–48010.","ja": "映像データを受信していません。多くはファイアウォールやポート転送で UDP 47998–48010 が許可されていないことが原因です。"},+ {+ "zh": "没有正在播放的画面,无法录制",+ "src": "src/ui/QmlPlayerBridge.cpp",+ "zh-TW": "沒有正在播放的畫面,無法錄製",+ "en": "Nothing is playing, so there is nothing to record",+ "ja": "再生中の映像がないため録画できません"+ },{"zh": "没有正在播放的画面,无法截图","src": "src/ui/QmlPlayerBridge.cpp",@@ -12413,6 +12588,13 @@"en": "Target bitrate: 1–300 Mbps. Actual VBR average bitrate varies with scene complexity.","ja": "目標ビットレートは 1~300 Mbps。VBR の実際の平均値は映像の複雑さによって変わります。"},+ {+ "zh": "目标码率,越高越清晰、文件也越大",+ "src": "qml/SettingsPage.qml",+ "zh-TW": "目標位元率,越高越清晰、檔案也越大",+ "en": "Target bitrate: higher means clearer and larger",+ "ja": "目標ビットレート:高いほど鮮明ですが、ファイルも大きくなります"+ },{"zh": "目标行数","src": "qml/DialogHost.qml",@@ -14436,6 +14618,13 @@"en": "Settings saved. Restart to apply them. Restart now? Current playback or streaming will stop.","ja": "設定を保存しました。適用するには再起動が必要です。今すぐ再起動しますか?再生やストリーミングは停止します。"},+ {+ "zh": "设置已变更,录制已结束",+ "src": "src/engine/EngineController.cpp",+ "zh-TW": "設定已變更,錄製已結束",+ "en": "The settings changed, so the recording ended",+ "ja": "設定が変更されたため、録画を終了しました"+ },{"zh": "设置应用失败,已恢复上一套参数","src": "src/engine/EngineController.cpp",@@ -15171,6 +15360,13 @@"en": "Follow the input signal","ja": "入力信号に合わせる"},+ {+ "zh": "跟随显示可录到补帧后的画面;限速则按该帧率抽帧",+ "src": "qml/SettingsPage.qml",+ "zh-TW": "跟隨顯示可錄到補幀後的畫面;限速則依該影格率抽幀",+ "en": "Follow the display to include generated frames; a limit samples at that rate",+ "ja": "表示に追従すると補間フレームも録画されます。制限時はそのフレームレートでサンプリングします"+ },{"zh": "跟随显示器","src": "qml/NodePage.qml",@@ -16081,6 +16277,13 @@"en": "Choose export folder","ja": "書き出し先フォルダーを選択"},+ {+ "zh": "选择录制保存位置",+ "src": "src/ui/QmlPlayerBridge.cpp",+ "zh-TW": "選擇錄製儲存位置",+ "en": "Choose the recording folder",+ "ja": "録画の保存先を選択"+ },{"zh": "选择截图目录","src": "src/ui/QmlPlayerBridge.cpp",@@ -18062,6 +18265,13 @@"en": "The default preset's edit mode is invalid","ja": "既定のプリセットの編集モードが不正です"},+ {+ "zh": "(MP4,只录处理后的画面,不含音频)",+ "src": "qml/SettingsPage.qml",+ "zh-TW": "(MP4,只錄製處理後的畫面,不含音訊)",+ "en": "(MP4, processed picture only, no audio)",+ "ja": "(MP4、処理後の映像のみ、音声なし)"+ },{"zh": "(NGX 0x{:08X},驱动 {}),已关闭依赖效果","src": "src/engine/EngineController.cpp",diff --git a/include/veyra/engine/EngineController.h b/include/veyra/engine/EngineController.hindex 01b33e0c..09c7dfa1 100644--- a/include/veyra/engine/EngineController.h+++ b/include/veyra/engine/EngineController.h@@ -26,6 +26,7 @@#include "veyra/media/NetworkSettings.h"#include "veyra/sink/VideoEncoder.h"#include "veyra/engine/ExportOptions.h"+#include "veyra/engine/LiveRecorder.h"namespace veyra::source { struct RemotePlayConnectDesc; class RemotePlaySessionSource; struct MoonlightConnectDesc; class MoonlightSessionSource; struct XboxConnectDesc; class XboxSessionSource; }namespace veyra::remoteplay { struct ControllerState;struct ControllerFeedback; }namespace veyra::sink { struct RgbaImage; }@@ -249,12 +250,20 @@ public:void saveFrame(const std::wstring& path);void startExport(const std::wstring& input,const std::wstring& output,PlayerOptions,bool hevc);PlayerSnapshot snapshot()const;+ // Live recording of the processed picture. The UI asks for it; the engine+ // thread owns the encoder and the file, so the GPU resources stay on one+ // thread and the playback loop keeps its cadence.+ void requestRecording(const RecordingOptions& options);+ void stopRecording();+ RecordingSnapshot recordingSnapshot()const;private:void run(HWND,std::wstring,PlayerOptions,std::shared_ptr<source::RemotePlayConnectDesc> remoteRequest={},std::shared_ptr<source::MoonlightConnectDesc> moonlightRequest={},std::shared_ptr<source::XboxConnectDesc> xboxRequest={});void runLargeImage(HWND,const sink::RgbaImage&,PlayerOptions,gfx::D3D12DeviceContext&,gfx::CommandSlotRing&);void post(std::function<void()>);void dispatch();void status(const std::wstring&,bool failed=false);+ // Copy the recorder state into the snapshot the UI reads.+ void publishRecordingStatus();void noteEngineHang(uint64_t stalledMs);#ifdef VEYRA_ENABLE_REMOTEPLAYvoid controlLoop(std::stop_token);@@ -281,6 +290,12 @@ private:std::shared_ptr<source::XboxSessionSource> activeXbox_;PreviewView previewView_;std::wstring savePath_;+ // Live recorder: the request comes from the UI thread, the encoder and the+ // file belong to the engine thread.+ std::unique_ptr<LiveRecorder> recorder_; // engine thread+ std::optional<RecordingOptions> recordingRequest_; // mutex_+ bool recordingStop_=false; // mutex_+ RecordingSnapshot recordingSnapshot_; // mutex_std::thread worker_;std::unique_ptr<PreviewGpuSession> prewarmed_; // engine dispatcher onlystd::atomic<bool> prewarmEnabled_{false}; // off until the saved preference enables it (default off since 2026-10-05)diff --git a/include/veyra/engine/LiveRecorder.h b/include/veyra/engine/LiveRecorder.hnew file mode 100644index 00000000..efeff02c--- /dev/null+++ b/include/veyra/engine/LiveRecorder.h@@ -0,0 +1,74 @@+#pragma once++// LiveRecorder: records the processed picture the engine presents.+//+// The recorder reuses the product video encoders (NVENC on NVIDIA, the+// driver's Media Foundation hardware MFT elsewhere) against the live+// enhancement graph, so the file holds the pixels the user actually sees+// after NR / SR / frame generation. Container writing runs on a private+// thread behind a bounded queue, so the playback loop never waits for the+// disk; when the queue is full the frame is dropped and counted instead of+// stalling playback.+//+// Scope for this first cut: video only (no audio track), MP4, one file per+// recording, and the presented frame. A settings change or a source switch+// rebuilds the graph, so the recorder closes the file at that point and says+// so instead of writing a file whose header no longer matches the frames.+#include <atomic>+#include <cstdint>+#include <memory>+#include <mutex>+#include <string>++namespace veyra::gfx { class D3D12DeviceContext; class CommandSlotRing; }+namespace veyra::pipeline { class EnhanceGraph; }++namespace veyra::engine {++struct RecordingSettings {+ std::wstring directory; // output folder (created when missing)+ uint32_t bitrateMbps = 20; // VBR target for the recorded file+ bool hevc = false; // false: H.264 (SDR), true: HEVC Main10+ uint32_t fpsLimit = 0; // 0: keep the presented rate+};++struct RecordingStatus {+ bool active = false;+ bool failed = false;+ std::wstring path; // file written (or being written)+ std::wstring error; // why it failed, when failed+ std::wstring encoder; // encoder identity, e.g. "NVIDIA NVENC H.264 (D3D12)"+ uint64_t frames = 0; // frames handed to the encoder+ uint64_t dropped = 0; // frames skipped because the writer fell behind+ double seconds = 0; // recorded length so far+};++class LiveRecorder {+public:+ LiveRecorder();+ ~LiveRecorder();+ LiveRecorder(const LiveRecorder&) = delete;+ LiveRecorder& operator=(const LiveRecorder&) = delete;++ // Engine thread only. Opens the encoder and the container; on failure the+ // reason is written to `error` and the recorder stays idle.+ bool begin(gfx::D3D12DeviceContext&, gfx::CommandSlotRing&, pipeline::EnhanceGraph&,+ const RecordingSettings&, uint32_t nominalFps, std::wstring& error);+ // Engine thread only. Encodes one presented frame; `generated` marks a+ // frame-generation output. Returns false when the recording failed and+ // was closed.+ bool encodeFrame(uint32_t frameSlot, bool generated);+ // Engine thread only. Finishes the file and releases the encoder.+ void end();+ // Any thread.+ bool active() const { return state_.load(std::memory_order_relaxed) == State::Recording; }+ RecordingStatus status() const;++private:+ enum class State { Idle, Recording, Failed };+ struct Impl;+ std::unique_ptr<Impl> p_;+ std::atomic<State> state_{State::Idle};+};++} // namespace veyra::enginediff --git a/include/veyra/sink/VideoEncoder.h b/include/veyra/sink/VideoEncoder.hindex fa2bf95f..de4e4d01 100644--- a/include/veyra/sink/VideoEncoder.h+++ b/include/veyra/sink/VideoEncoder.h@@ -57,6 +57,11 @@ struct EncoderConfig {// host), so the Media Foundation path must prefer the MFT of the GPU that// actually renders the frames. 0x10DE/0x1002/0x8086 = NVIDIA/AMD/Intel.uint32_t adapterVendorId=0;+ // How long a bitstream drain may wait for the GPU before the encoder+ // gives up. The export can afford a long wait; the live recorder runs+ // inside the playback loop and keeps this short so a slow GPU cannot+ // stall playback behind the recorder.+ uint32_t drainTimeoutMs=10000;};class VideoEncoder {diff --git a/include/veyra/ui/QmlPlayerBridge.h b/include/veyra/ui/QmlPlayerBridge.hindex 4a05530e..08b38969 100644--- a/include/veyra/ui/QmlPlayerBridge.h+++ b/include/veyra/ui/QmlPlayerBridge.h@@ -219,6 +219,14 @@ class QmlPlayerBridge : public QObject {Q_PROPERTY(QString uiLanguage READ uiLanguage NOTIFY preferencesChanged)Q_PROPERTY(QString screenshotDirectory READ screenshotDirectory NOTIFY preferencesChanged)Q_PROPERTY(QString lastScreenshot READ lastScreenshot NOTIFY preferencesChanged)+ // Live recording of the processed picture: the engine owns the encoder and+ // the file, the interface shows the state and starts or stops it.+ Q_PROPERTY(bool recording READ recording NOTIFY recordingChanged)+ Q_PROPERTY(QVariantMap recordingState READ recordingState NOTIFY recordingChanged)+ Q_PROPERTY(QString recordingDirectory READ recordingDirectory NOTIFY preferencesChanged)+ Q_PROPERTY(int recordingBitrateMbps READ recordingBitrateMbps NOTIFY preferencesChanged)+ Q_PROPERTY(int recordingFpsLimit READ recordingFpsLimit NOTIFY preferencesChanged)+ Q_PROPERTY(bool recordingHevc READ recordingHevc NOTIFY preferencesChanged)Q_PROPERTY(QString dataDirectory READ dataDirectory CONSTANT)// Rebindable shortcuts: action -> key sequence text (defaults merged in).Q_PROPERTY(QVariantMap shortcuts READ shortcuts NOTIFY preferencesChanged)@@ -1258,6 +1266,19 @@ public:Q_INVOKABLE void setWindowMask(QObject* window, const QRectF& rect);Q_INVOKABLE void stepFrame(int direction);Q_INVOKABLE void takeScreenshot();+ // Recording: the 3 second countdown lives in the interface, the engine+ // only opens the file when the request reaches it.+ Q_INVOKABLE void startRecording();+ Q_INVOKABLE void stopRecording();+ Q_INVOKABLE void toggleRecording();+ Q_INVOKABLE void chooseRecordingDirectory();+ Q_INVOKABLE void openRecordingDirectory();+ bool recording() const;+ QVariantMap recordingState() const;+ QString recordingDirectory() const;+ int recordingBitrateMbps() const;+ int recordingFpsLimit() const;+ bool recordingHevc() const;Q_INVOKABLE void chooseExportPath();// The export target without the dialog (the dialog's result, or --export-out in a test).void setExportPath(const QString& path);@@ -1327,6 +1348,7 @@ signals:void subtitlesChanged();void subtitleTextChanged();void preferencesChanged();+ void recordingChanged();void colourLibraryChanged();// Emitted only when the underlying snapshot actually changed, so QML// bindings do not re-evaluate 60 times a second for nothing.diff --git a/qml/Veyra/ProPage.qml b/qml/Veyra/ProPage.qmlindex d722a9bb..0e09c8d6 100644--- a/qml/Veyra/ProPage.qml+++ b/qml/Veyra/ProPage.qml@@ -613,6 +613,95 @@ VPage {}}VButton { iconName: "camera"; text: qsTr("截图"); onClicked: veyra.takeScreenshot() }+ // Recording: the red dot pulses while the file is open, and a+ // three second countdown runs before the engine is asked to open+ // it. The countdown is an interface animation; the file itself is+ // owned by the engine.+ Item {+ id: recordControl+ objectName: "pro-record-control"+ anchors.verticalCenter: parent.verticalCenter+ width: recordButton.implicitWidth+ height: recordButton.implicitHeight+ property int countdown: 0++ Rectangle {+ id: recordButton+ objectName: "pro-record-button"+ anchors.fill: parent+ implicitWidth: recordRow.implicitWidth + 24+ implicitHeight: Theme.ctlHeight+ radius: Theme.rCtl+ color: recordMouse.containsMouse ? Theme.card3 : Theme.card2+ border.width: 1+ border.color: (veyra.recording || recordControl.countdown > 0) ? Theme.err : Theme.stroke2+ Behavior on color { ColorAnimation { duration: Theme.d(Theme.durFast) } }+ Behavior on border.color { ColorAnimation { duration: Theme.d(Theme.durFast) } }++ Row {+ id: recordRow+ anchors.centerIn: parent+ spacing: 7+ Rectangle {+ id: recordDot+ width: 9; height: 9; radius: 4.5+ anchors.verticalCenter: parent.verticalCenter+ color: Theme.err+ SequentialAnimation on opacity {+ running: veyra.recording || recordControl.countdown > 0+ loops: Animation.Infinite+ NumberAnimation { to: 0.25; duration: veyra.recording ? 700 : 380; easing.type: Easing.InOutQuad }+ NumberAnimation { to: 1.0; duration: veyra.recording ? 700 : 380; easing.type: Easing.InOutQuad }+ }+ }+ Text {+ id: recordLabel+ anchors.verticalCenter: parent.verticalCenter+ text: recordControl.countdown > 0 ? qsTr("录制 %1 秒").arg(recordControl.countdown)+ : (veyra.recording ? qsTr("停止录制") : qsTr("录制"))+ color: Theme.t1+ font.family: Theme.fontUi+ font.pixelSize: Theme.fsBody+ font.weight: Font.Medium+ }+ }+ MouseArea {+ id: recordMouse+ anchors.fill: parent+ hoverEnabled: true+ cursorShape: Qt.PointingHandCursor+ onClicked: {+ if (veyra.recording) { veyra.stopRecording(); recordControl.countdown = 0; recordTick.stop(); return }+ if (recordControl.countdown > 0) { recordControl.countdown = 0; recordTick.stop(); return }+ recordControl.countdown = 3+ recordTick.restart()+ }+ }+ }+ Timer {+ id: recordTick+ interval: 1000+ repeat: true+ onTriggered: {+ recordControl.countdown -= 1+ recordPop.restart()+ if (recordControl.countdown <= 0) {+ recordControl.countdown = 0+ recordTick.stop()+ veyra.startRecording()+ }+ }+ }+ }+ NumberAnimation {+ id: recordPop+ target: recordLabel+ property: "scale"+ from: 1.18+ to: 1.0+ duration: Theme.d(Theme.durFast)+ easing.type: Theme.spring+ }VButton {id: presetBtniconName: "layers"diff --git a/qml/Veyra/SettingsPage.qml b/qml/Veyra/SettingsPage.qmlindex 1c0410d8..b0f400cf 100644--- a/qml/Veyra/SettingsPage.qml+++ b/qml/Veyra/SettingsPage.qml@@ -551,6 +551,48 @@ VPage {VButton { objectName: "set-shotdir"; text: qsTr("更改…"); onClicked: veyra.chooseScreenshotDirectory() }}}+ VGroup {+ objectName: "set-recording"+ VRow {+ label: qsTr("录制保存位置")+ hint: veyra.recordingDirectory + qsTr("(MP4,只录处理后的画面,不含音频)")+ RowLayout {+ spacing: 6+ VButton { text: qsTr("打开"); ghost: true; onClicked: veyra.openRecordingDirectory() }+ VButton { objectName: "set-recdir"; text: qsTr("更改…"); onClicked: veyra.chooseRecordingDirectory() }+ }+ }+ VRow {+ label: qsTr("录制码率")+ hint: qsTr("目标码率,越高越清晰、文件也越大")+ VSeg {+ objectName: "set-recbitrate"+ options: [{ id: "8", label: "8" }, { id: "16", label: "16" }, { id: "20", label: "20" }, { id: "40", label: "40" }, { id: "80", label: "80" }]+ current: String(veyra.recordingBitrateMbps)+ onPicked: id => veyra.setPreference("recordBitrateMbps", Number(id))+ }+ }+ VRow {+ label: qsTr("录制帧率")+ hint: qsTr("跟随显示可录到补帧后的画面;限速则按该帧率抽帧")+ VSeg {+ objectName: "set-recfps"+ options: [{ id: "0", label: qsTr("跟随") }, { id: "30", label: "30" }, { id: "60", label: "60" }]+ current: String(veyra.recordingFpsLimit)+ onPicked: id => veyra.setPreference("recordFps", Number(id))+ }+ }+ VRow {+ label: qsTr("录制编码")+ hint: qsTr("HDR 画面固定使用 HEVC 10bit")+ VSeg {+ objectName: "set-rechevc"+ options: [{ id: "0", label: "H.264" }, { id: "1", label: "HEVC" }]+ current: veyra.recordingHevc ? "1" : "0"+ onPicked: id => veyra.setPreference("recordHevc", id === "1")+ }+ }+ }}VGroup {objectName: "set-smooth-motion"diff --git a/src/engine/EngineController.cpp b/src/engine/EngineController.cppindex f1bd7995..aca90910 100644--- a/src/engine/EngineController.cpp+++ b/src/engine/EngineController.cpp@@ -3,6 +3,7 @@#include "veyra/engine/PreviewFrameReadiness.h"#include "veyra/engine/FgCompatibilityProbe.h"#include "veyra/engine/VideoPresenter.h"+#include "veyra/engine/LiveRecorder.h"#include "veyra/engine/HdrDisplayState.h"#include "veyra/engine/VideoExportJob.h"#include "veyra/engine/LivePresentationTiming.h"@@ -365,6 +366,23 @@ bool EngineController::requestSettings(EnhancementSettings s,std::optional<Chainif(acceptedRevision)*acceptedRevision=s.revision;return true;}void EngineController::saveFrame(const std::wstring& path){std::lock_guard lock(mutex_);savePath_=path;}+void EngineController::requestRecording(const RecordingOptions& options){+ // The UI thread only records the request; the engine thread owns the+ // encoder, the GPU resources and the file.+ {std::lock_guard lock(mutex_);recordingRequest_=options;}+ veyra::log::info("live-recorder",std::format("request directory={} bitrateMbps={} hevc={} fpsLimit={}",std::string(options.directory.begin(),options.directory.end()),options.bitrateMbps,options.hevc?1:0,options.fpsLimit));+}+void EngineController::stopRecording(){std::lock_guard lock(mutex_);recordingStop_=true;}+void EngineController::publishRecordingStatus(){+ if(!recorder_){std::lock_guard lock(mutex_);recordingSnapshot_={};return;}+ const auto live=recorder_->status();+ std::lock_guard lock(mutex_);+ recordingSnapshot_.active=live.active;recordingSnapshot_.failed=live.failed;+ recordingSnapshot_.path=live.path;recordingSnapshot_.error=live.error;+ recordingSnapshot_.encoder=live.encoder;recordingSnapshot_.frames=live.frames;+ recordingSnapshot_.dropped=live.dropped;recordingSnapshot_.seconds=live.seconds;+}+RecordingSnapshot EngineController::recordingSnapshot()const{std::lock_guard lock(mutex_);return recordingSnapshot_;}void EngineController::startExport(const std::wstring& input,const std::wstring& output,PlayerOptions opts,bool hevc){if(opts.nodeOrder){veyra::log::warn("node-order","export has no runtime node-order transport; request rejected before posting");@@ -461,6 +479,9 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,sCoInitializeEx(nullptr,COINIT_MULTITHREADED);MmcssScope mmcss(L"Pro Audio");status(L"正在初始化GPU与本地运行时…");+ // A new session replaces the graph, so a recording from the previous one+ // cannot continue into it.+ if(recorder_&&recorder_->active()){recorder_->end();publishRecordingStatus();}auto extension=std::filesystem::path(path).extension().wstring();for(auto& c:extension)c=towlower(c);const bool ordinaryFile=!remoteRequest&&!moonlightRequest&&!xboxRequest&&!path.starts_with(L"capture:")&&!path.starts_with(L"capture2:")&&!path.starts_with(L"screen:")&&@@ -1179,7 +1200,10 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,smarkResetStage(diagnostics::ResetStage::FirstValid);finishReset(diagnostics::ResetOutcome::Completed);};- OnExit resetExit{[&]{finishReset(stop_?diagnostics::ResetOutcome::Cancelled:diagnostics::ResetOutcome::Failed);}};+ OnExit resetExit{[&]{finishReset(stop_?diagnostics::ResetOutcome::Cancelled:diagnostics::ResetOutcome::Failed);+ // The session owns the recorder: close the file on every exit+ // path so the container is finalized.+ if(recorder_&&recorder_->active()){recorder_->end();publishRecordingStatus();}};auto collectTimings=[&]{auto record=[&](const diagnostics::GpuFrameTiming& sample){const auto& fgCost=sample.gpu[size_t(diagnostics::GpuStage::FgBatch)];@@ -1535,6 +1559,24 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,sdrainLivePresentation();if(graph->hdrOutput()){auto hdrPath=std::filesystem::path(save);hdrPath.replace_extension(L".jxr");if(sink::saveHdrScreenshot(hdrPath.wstring(),ctx,ring,graph->videoFrameResource(out.videoSlot)))status(L"HDR截图已保存:"+hdrPath.wstring());else status(L"HDR截图保存失败,请查看日志",false);}else if(!sink::readRgba8(ctx,ring,graph->videoFrameResource(out.videoSlot),result)||!sink::saveImage(save,result,e==L".jpg"||e==L".jpeg"))status(L"保存失败(目标文件可能已存在),播放已保留",false);else{status(L"图片已保存:"+save);veyra::log::info("image-save",std::format("saved extent={}x{} revision={}",gd.workWidth,gd.workHeight,options.settings.revision));}}catch(const std::exception& e){veyra::log::warn("image-save",std::format("save exception; retaining session: {}",e.what()));status(L"保存异常,播放已保留;可再次保存",false);}}+ // Recording requests arrive from the UI thread; the encoder+ // belongs to this thread, which owns the GPU context.+ {+ std::optional<RecordingOptions> request;bool stop=false;+ {std::lock_guard lock(mutex_);request=recordingRequest_;recordingRequest_.reset();stop=recordingStop_;recordingStop_=false;}+ if(stop&&recorder_&&recorder_->active()){recorder_->end();publishRecordingStatus();status(L"录制已结束",false);}+ if(request){+ if(recorder_&&recorder_->active()){status(L"录制已在进行中",false);}+ else{+ double nominal=0;{std::lock_guard lock(mutex_);nominal=snapshot_.nominalSourceFps;}+ const uint32_t fps=nominal>1.0?uint32_t(std::llround(nominal)):60u;+ std::wstring error;+ if(!recorder_)recorder_=std::make_unique<LiveRecorder>();+ if(recorder_->begin(ctx,ring,*graph,*request,fps,error)){publishRecordingStatus();status(L"开始录制");}+ else{publishRecordingStatus();status(error.empty()?L"无法开始录制":error,true);}+ }+ }+ }if(isImage)requested.multiplier=1;if(requested.revision==options.settings.revision&&requested!=options.settings){options.settings.audioSync=requested.audioSync;options.settings.audioOffsetMs=requested.audioOffsetMs;@@ -1567,6 +1609,9 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s}const auto previous=options.snapshot();const auto previousDesc=gd;const auto previousOrder=options.nodeOrder;bool transaction=false;if(requested.revision!=previous.revision){+ // The rebuild replaces the graph and its textures, which+ // the recorder registered: close the file before that.+ if(recorder_&&recorder_->active()){recorder_->end();publishRecordingStatus();status(L"设置已变更,录制已结束",false);}holdFileAudio();finishReset(diagnostics::ResetOutcome::Cancelled);resetStart=resetStageStart=Clock::now();@@ -2582,6 +2627,12 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s// work. The bounded scheduler retains that pressure.}if(didPresent){+ // Record what was presented. A provider-owned+ // presentation (XeSS) has no graph texture to+ // encode, so only the real frames are recorded+ // there - the same limit the export states.+ if(recorder_&&recorder_->active()&&!(generated&&presenter.providerOwnedPresentation()))+ recorder_->encodeFrame(item.lease->slot,generated);cadence.submitted(optionalNow);cadence.rateSubmitted(optionalNow,capInterval);if(physicalCapture&&veyra::log::verboseFrameLogs())veyra::log::info("capture-present-sample",std::format("source={} epoch={} revision={} batch={} subframe={} generated={} arrival={} arrivalA={} ready={} begin={} end={}",item.identity.sourceFrameId,item.identity.epoch,item.identity.settingsRevision,batch.batch.batchId,item.subframe,generated,captureArrival,lineage?lineage->a.host100ns:0,watch->frameReadyObserved[s.next],optionalNow,host100ns()));diff --git a/src/engine/LiveRecorder.cpp b/src/engine/LiveRecorder.cppnew file mode 100644index 00000000..60d060fe--- /dev/null+++ b/src/engine/LiveRecorder.cpp@@ -0,0 +1,341 @@+#include "veyra/engine/LiveRecorder.h"+#include "veyra/pipeline/EnhanceGraph.h"+#include "veyra/gfx/D3D12DeviceContext.h"+#include "veyra/gfx/CommandSlotRing.h"+#include "veyra/sink/VideoEncoder.h"+#include "veyra/Log.h"++#include <algorithm>+#include <chrono>+#include <condition_variable>+#include <cstring>+#include <ctime>+#include <deque>+#include <format>+#include <filesystem>+#include <thread>+#include <vector>++extern "C" {+#include <libavformat/avformat.h>+#include <libavcodec/avcodec.h>+#include <libavutil/mathematics.h>+}++namespace veyra::engine {+namespace {++std::string utf8(const std::wstring& text) {+ if (text.empty()) return {};+ const int size = WideCharToMultiByte(CP_UTF8, 0, text.data(), int(text.size()), nullptr, 0, nullptr, nullptr);+ std::string out(size, 0);+ WideCharToMultiByte(CP_UTF8, 0, text.data(), int(text.size()), out.data(), size, nullptr, nullptr);+ return out;+}++std::wstring fileStamp() {+ const std::time_t now = std::time(nullptr);+ std::tm local{};+ localtime_s(&local, &now);+ wchar_t buffer[32]{};+ swprintf_s(buffer, L"%04d-%02d-%02d-%02d%02d%02d", local.tm_year + 1900, local.tm_mon + 1, local.tm_mday,+ local.tm_hour, local.tm_min, local.tm_sec);+ return buffer;+}++} // namespace++struct LiveRecorder::Impl {+ struct Packet {+ std::vector<uint8_t> data;+ int64_t ptsUs = 0;+ int64_t durationUs = 0;+ bool key = false;+ };++ // The engine thread produces packets; the writer thread owns the file.+ // The queue is bounded so a slow disk costs frames, never playback.+ static constexpr size_t kQueueLimit = 240; // ~4 s of 60 fps video+ static constexpr size_t kQueueHighWater = 160; // start dropping here++ std::unique_ptr<sink::VideoEncoder> encoder;+ AVFormatContext* mux = nullptr;+ AVStream* stream = nullptr;+ std::thread writer;++ std::mutex queueMutex;+ std::condition_variable queueSignal;+ std::deque<Packet> queue;+ bool writerStop = false;+ std::atomic<bool> writerFailed{false};+ std::atomic<bool> headerWritten{false};++ mutable std::mutex statusMutex;+ std::wstring path;+ std::wstring error;+ std::wstring encoderName;++ uint32_t width = 0, height = 0, fps = 60;+ bool hevc = false, hdr = false;+ int64_t frameDurationUs = 16667;+ int64_t lastPtsUs = -1;+ std::atomic<uint64_t> frames{0};+ std::atomic<uint64_t> dropped{0};+ std::atomic<uint64_t> recordedUs{0};+ std::chrono::steady_clock::time_point startTime{};++ void failWriter(const std::wstring& reason) {+ writerFailed.store(true, std::memory_order_relaxed);+ {+ std::lock_guard lock(statusMutex);+ if (error.empty()) error = reason;+ }+ veyra::log::error("live-recorder", std::format("writer failed: {}",+ std::string(error.begin(), error.end())));+ }++ bool writePacket(const Packet& packet) {+ AVPacket* raw = av_packet_alloc();+ if (!raw) return false;+ bool ok = av_new_packet(raw, int(packet.data.size())) >= 0;+ if (ok) {+ std::memcpy(raw->data, packet.data.data(), packet.data.size());+ raw->stream_index = stream->index;+ raw->pts = raw->dts = packet.ptsUs;+ raw->duration = packet.durationUs;+ if (packet.key) raw->flags |= AV_PKT_FLAG_KEY;+ ok = av_interleaved_write_frame(mux, raw) >= 0;+ }+ av_packet_free(&raw);+ return ok;+ }++ void writerLoop() {+ int result = avio_open(&mux->pb, utf8(path).c_str(), AVIO_FLAG_WRITE);+ if (result < 0) { failWriter(L"无法创建录制文件"); return; }+ result = avformat_write_header(mux, nullptr);+ if (result < 0) {+ avio_closep(&mux->pb);+ failWriter(L"无法写入录制文件头");+ return;+ }+ headerWritten.store(true, std::memory_order_relaxed);+ veyra::log::info("live-recorder", std::format("container header written path={}",+ std::string(utf8(path).begin(), utf8(path).end())));+ for (;;) {+ Packet packet;+ {+ std::unique_lock lock(queueMutex);+ queueSignal.wait(lock, [this] { return writerStop || !queue.empty(); });+ if (queue.empty()) {+ if (writerStop) break;+ continue;+ }+ packet = std::move(queue.front());+ queue.pop_front();+ }+ if (!writePacket(packet)) { failWriter(L"写入录制帧失败"); break; }+ }+ if (headerWritten.load(std::memory_order_relaxed)) av_write_trailer(mux);+ if (mux && mux->pb) avio_closep(&mux->pb);+ veyra::log::info("live-recorder", "container closed");+ }+};++LiveRecorder::LiveRecorder() : p_(std::make_unique<Impl>()) {}+LiveRecorder::~LiveRecorder() { end(); }++bool LiveRecorder::begin(gfx::D3D12DeviceContext& ctx, gfx::CommandSlotRing& ring, pipeline::EnhanceGraph& graph,+ const RecordingSettings& settings, uint32_t nominalFps, std::wstring& error) {+ auto& p = *p_;+ error.clear();+ if (state_.load(std::memory_order_relaxed) != State::Idle) { error = L"录制已在进行中"; return false; }+ if (settings.directory.empty()) { error = L"未设置录制保存位置"; return false; }+ std::error_code code;+ std::filesystem::create_directories(settings.directory, code);+ if (code) { error = L"无法创建录制目录:" + settings.directory; return false; }++ const auto file = (std::filesystem::path(settings.directory) / (L"Veyra-" + fileStamp() + L".mp4")).wstring();+ if (std::filesystem::exists(file)) { error = L"录制文件已存在,请更换保存位置"; return false; }++ // The recorded picture is the processed one: the graph's working extent.+ p.width = graph.workWidth();+ p.height = graph.workHeight();+ if (!p.width || !p.height) { error = L"当前画面尺寸不可用"; return false; }+ if ((p.width & 1) || (p.height & 1)) { error = L"当前画面尺寸为奇数,无法录制"; return false; }+ p.hdr = graph.hdrOutput();+ // HDR output needs HEVC Main10; the encoder refuses H.264 for 10-bit.+ p.hevc = settings.hevc || p.hdr;+ p.fps = settings.fpsLimit ? settings.fpsLimit : (nominalFps ? nominalFps : 60);+ if (p.fps > 240) p.fps = 240;+ p.frameDurationUs = 1000000 / p.fps;+ {+ std::lock_guard lock(p.statusMutex);+ p.path = file;+ p.error.clear();+ }++ if (avformat_alloc_output_context2(&p.mux, nullptr, "mp4", nullptr) < 0 || !p.mux) {+ error = L"无法创建录制封装器";+ return false;+ }+ p.stream = avformat_new_stream(p.mux, nullptr);+ if (!p.stream) { error = L"无法创建录制视频流"; return false; }+ p.stream->time_base = AVRational{1, 1000000};+ p.stream->avg_frame_rate = AVRational{int(p.fps), 1};+ auto* parameters = p.stream->codecpar;+ parameters->codec_type = AVMEDIA_TYPE_VIDEO;+ parameters->codec_id = p.hevc ? AV_CODEC_ID_HEVC : AV_CODEC_ID_H264;+ parameters->width = p.width;+ parameters->height = p.height;+ parameters->format = p.hdr ? AV_PIX_FMT_YUV420P10LE : AV_PIX_FMT_YUV420P;+ parameters->color_range = AVCOL_RANGE_MPEG;+ parameters->color_space = p.hdr ? AVCOL_SPC_BT2020_NCL : AVCOL_SPC_BT709;+ parameters->color_primaries = p.hdr ? AVCOL_PRI_BT2020 : AVCOL_PRI_BT709;+ parameters->color_trc = p.hdr ? AVCOL_TRC_SMPTE2084 : AVCOL_TRC_IEC61966_2_1;+ if (p.hdr) parameters->profile = AV_PROFILE_HEVC_MAIN_10;++ // The engine thread produces packets; the writer thread owns the file.+ auto producer = [this](const uint8_t* bytes, size_t size, int64_t pts, bool key) {+ Impl::Packet packet;+ packet.data.assign(bytes, bytes + size);+ packet.ptsUs = pts;+ packet.durationUs = p_->frameDurationUs;+ packet.key = key;+ {+ std::lock_guard lock(p_->queueMutex);+ if (p_->queue.size() >= Impl::kQueueLimit) {+ p_->dropped.fetch_add(1, std::memory_order_relaxed);+ return false; // the encoder stops instead of writing a broken file+ }+ p_->queue.push_back(std::move(packet));+ }+ p_->queueSignal.notify_one();+ return true;+ };++ sink::EncoderConfig config;+ config.hevc = p.hevc;+ config.fpsNum = p.fps;+ config.fpsDen = 1;+ config.bitrateMbps = settings.bitrateMbps;+ config.rateControl = sink::ExportRateControl::Vbr;+ // The live loop may not wait long for the encoder: a bounded drain keeps+ // a slow GPU from stalling playback behind the recorder.+ config.drainTimeoutMs = 2000;+ std::wstring detail;+ p.encoder = sink::openVideoEncoder(ctx, ring, graph, config, producer, detail);+ if (!p.encoder) {+ error = detail.empty() ? L"没有可用的视频编码器" : detail;+ if (p.mux) { avformat_free_context(p.mux); p.mux = nullptr; }+ return false;+ }+ {+ std::lock_guard lock(p.statusMutex);+ p.encoderName = p.encoder->describe();+ }+ const auto headers = p.encoder->headers();+ if (!headers.empty()) {+ parameters->extradata = static_cast<uint8_t*>(av_mallocz(headers.size() + AV_INPUT_BUFFER_PADDING_SIZE));+ if (!parameters->extradata) { error = L"无法写入录制文件头"; return false; }+ std::memcpy(parameters->extradata, headers.data(), headers.size());+ parameters->extradata_size = int(headers.size());+ }++ p.frames.store(0, std::memory_order_relaxed);+ p.dropped.store(0, std::memory_order_relaxed);+ p.recordedUs.store(0, std::memory_order_relaxed);+ p.lastPtsUs = -1;+ p.startTime = std::chrono::steady_clock::now();+ p.writer = std::thread([this] { p_->writerLoop(); });+ state_.store(State::Recording, std::memory_order_release);+ veyra::log::info("live-recorder", std::format(+ "started path={} extent={}x{} codec={} hdr={} fps={} bitrateMbps={} encoder={}",+ std::string(utf8(file).begin(), utf8(file).end()), p.width, p.height, p.hevc ? "HEVC" : "H264",+ p.hdr ? 1 : 0, p.fps, settings.bitrateMbps,+ std::string(utf8(p.encoderName).begin(), utf8(p.encoderName).end())));+ return true;+}++bool LiveRecorder::encodeFrame(uint32_t frameSlot, bool generated) {+ auto& p = *p_;+ if (state_.load(std::memory_order_relaxed) != State::Recording) return false;+ if (p.writerFailed.load(std::memory_order_relaxed)) { end(); return false; }++ // A slow disk costs frames, never playback: above the high-water mark the+ // frame is skipped and counted.+ if (p.queue.size() >= Impl::kQueueHighWater) {+ p.dropped.fetch_add(1, std::memory_order_relaxed);+ return true;+ }+ const auto now = std::chrono::steady_clock::now();+ const int64_t ptsUs = std::chrono::duration_cast<std::chrono::microseconds>(now - p.startTime).count();+ if (p.lastPtsUs >= 0 && ptsUs <= p.lastPtsUs) return true; // monotonic only+ p.lastPtsUs = ptsUs;+ p.recordedUs.store(uint64_t(ptsUs), std::memory_order_relaxed);+ if (!p.encoder->encode(frameSlot, generated, ptsUs)) {+ {+ std::lock_guard lock(p.statusMutex);+ if (p.error.empty()) p.error = p.encoder->lastError();+ }+ veyra::log::error("live-recorder", "encode failed; closing the recording");+ end();+ return false;+ }+ p.frames.fetch_add(1, std::memory_order_relaxed);+ return true;+}++void LiveRecorder::end() {+ auto& p = *p_;+ const State state = state_.load(std::memory_order_relaxed);+ if (state == State::Idle) {+ // A failed begin() may still own a container context.+ if (p.mux) { avformat_free_context(p.mux); p.mux = nullptr; }+ return;+ }+ state_.store(State::Idle, std::memory_order_release);+ // Drain the encoder first: the last bitstreams reach the writer through+ // the same queue, and the trailer may only be written after them.+ if (p.encoder) {+ if (!p.encoder->finish()) {+ std::lock_guard lock(p.statusMutex);+ if (p.error.empty()) p.error = p.encoder->lastError();+ }+ p.encoder.reset();+ }+ {+ std::lock_guard lock(p.queueMutex);+ p.writerStop = true;+ }+ p.queueSignal.notify_all();+ if (p.writer.joinable()) p.writer.join();+ if (p.mux) {+ avformat_free_context(p.mux);+ p.mux = nullptr;+ p.stream = nullptr;+ }+ const bool failed = p.writerFailed.load(std::memory_order_relaxed) || !p.error.empty();+ state_.store(failed ? State::Failed : State::Idle, std::memory_order_release);+ veyra::log::info("live-recorder", std::format(+ "stopped path={} frames={} dropped={} seconds={:.2f} failed={}",+ std::string(utf8(p.path).begin(), utf8(p.path).end()), p.frames.load(), p.dropped.load(),+ double(p.recordedUs.load()) / 1000000.0, failed ? 1 : 0));+}++RecordingStatus LiveRecorder::status() const {+ auto& p = *p_;+ RecordingStatus out;+ out.active = state_.load(std::memory_order_relaxed) == State::Recording;+ out.frames = p.frames.load(std::memory_order_relaxed);+ out.dropped = p.dropped.load(std::memory_order_relaxed);+ out.seconds = double(p.recordedUs.load(std::memory_order_relaxed)) / 1000000.0;+ std::lock_guard lock(p.statusMutex);+ out.path = p.path;+ out.error = p.error;+ out.encoder = p.encoderName;+ out.failed = !p.error.empty();+ return out;+}++} // namespace veyra::enginediff --git a/src/sink/MfVideoEncoder.cpp b/src/sink/MfVideoEncoder.cppindex 017f216a..fb332d46 100644--- a/src/sink/MfVideoEncoder.cpp+++ b/src/sink/MfVideoEncoder.cpp@@ -193,6 +193,7 @@ private:bool hevc_=false;uint32_t bitrateMbps_=0;ExportRateControl rateControl_=ExportRateControl::Cq;+ uint32_t drainTimeoutMs_=10000;unsigned fpsNum_=1,fpsDen_=1;uint32_t width_=0,height_=0;ComputePass convert_;@@ -211,6 +212,7 @@ private:bool MfVideoEncoder::open(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing& ring,EnhanceGraph& graph,const EncoderConfig& config,PacketWriter writer){ctx_=&ctx;ring_=˚graph_=&graph;writer_=std::move(writer);hevc_=config.hevc;bitrateMbps_=config.bitrateMbps;rateControl_=config.rateControl;+ drainTimeoutMs_=config.drainTimeoutMs?config.drainTimeoutMs:10000;fpsNum_=std::max(1u,config.fpsNum);fpsDen_=std::max(1u,config.fpsDen);width_=graph.workWidth();height_=graph.workHeight();error_=L"Media Foundation startup failed; see worker log";@@ -594,7 +596,7 @@ bool MfVideoEncoder::convertToNv12(unsigned frameSlot,bool generated){// (never-signalled) fence here was the first-frame timeout.const uint64_t value=ring_->lastSignaledValue();if(ctx_->fence()->GetCompletedValue()<value){- if(FAILED(ctx_->fence()->SetEventOnCompletion(value,fenceEvent_))||WaitForSingleObject(fenceEvent_,10000)!=WAIT_OBJECT_0){+ if(FAILED(ctx_->fence()->SetEventOnCompletion(value,fenceEvent_))||WaitForSingleObject(fenceEvent_,drainTimeoutMs_)!=WAIT_OBJECT_0){log::error("mf-encoder",std::format("readback fence wait failed value={}",value));return false;}diff --git a/src/sink/NvencD3D12Encoder.cpp b/src/sink/NvencD3D12Encoder.cppindex 1578a51a..509e4607 100644--- a/src/sink/NvencD3D12Encoder.cpp+++ b/src/sink/NvencD3D12Encoder.cpp@@ -18,6 +18,7 @@ struct NvencD3D12Encoder::Impl {bool hdr=false;bool hevc=false;NV_ENC_BUFFER_FORMAT inputFormat=NV_ENC_BUFFER_FORMAT_NV12;unsigned w=0,h=0;uint64_t submitted=0,completed=0;uint32_t bitrateMbps=0;+ uint32_t drainTimeoutMs=10000;std::wstring error;bool fail(std::wstring message){error=std::move(message);veyra::log::error("nvenc",std::string(error.begin(),error.end()));return false;}ComPtr<ID3D12Fence> fence;HANDLE event=nullptr;@@ -32,7 +33,7 @@ struct NvencD3D12Encoder::Impl {if(code!=NV_ENC_SUCCESS||successLogs<24||veyra::log::verboseFrameLogs()){if(code==NV_ENC_SUCCESS)++successLogs;veyra::log::info("nvenc",std::format("{} status={} detail={}",op,int(code),detail));}if(code!=NV_ENC_SUCCESS){const auto text=std::format("{} status={} {}",op,int(code),detail);error.assign(text.begin(),text.end());}return code==NV_ENC_SUCCESS;}bool drain(Slot& s){if(!s.pending)return true;- if(fence->GetCompletedValue()<s.value){if(FAILED(fence->SetEventOnCompletion(s.value,event))||WaitForSingleObject(event,10000)!=WAIT_OBJECT_0)return false;}+ if(fence->GetCompletedValue()<s.value){if(FAILED(fence->SetEventOnCompletion(s.value,event))||WaitForSingleObject(event,p.drainTimeoutMs)!=WAIT_OBJECT_0)return false;}NV_ENC_LOCK_BITSTREAM lock{};lock.version=NV_ENC_LOCK_BITSTREAM_VER;lock.outputBitstream=&s.out;lock.doNotWait=0;if(!check(api.nvEncLockBitstream(encoder,&lock),"LockBitstream"))return false;const bool ok=writer(static_cast<uint8_t*>(lock.bitstreamBufferPtr),lock.bitstreamSizeInBytes,static_cast<int64_t>(lock.outputTimeStamp),lock.pictureType==NV_ENC_PIC_TYPE_IDR);@@ -51,6 +52,7 @@ bool NvencD3D12Encoder::open(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing&const bool hevc=config.hevc;const unsigned fpsNum=config.fpsNum,fpsDen=config.fpsDen;auto& p=*p_;p.ctx=&ctx;p.ring=˚p.graph=&graph;p.w=graph.workWidth();p.h=graph.workHeight();p.writer=std::move(writer);p.hevc=hevc;p.bitrateMbps=config.bitrateMbps;+ p.drainTimeoutMs=config.drainTimeoutMs?config.drainTimeoutMs:10000;p.error=L"NVENC initialization incomplete";wchar_t dir[MAX_PATH]{};GetSystemDirectoryW(dir,MAX_PATH);const auto dllPath=std::wstring(dir)+L"\\nvEncodeAPI64.dll";p.dll=LoadLibraryExW(dllPath.c_str(),nullptr,LOAD_LIBRARY_SEARCH_SYSTEM32);if(!p.dll)return p.fail(std::format(L"LoadLibrary nvEncodeAPI64.dll win32={}",GetLastError()));diff --git a/src/ui/QmlPlayerBridge.cpp b/src/ui/QmlPlayerBridge.cppindex 7d3112b3..a4a47ecb 100644--- a/src/ui/QmlPlayerBridge.cpp+++ b/src/ui/QmlPlayerBridge.cpp@@ -347,6 +347,8 @@ struct QmlPlayerBridge::Impl {// Declared after everything the worker touches, so it is joined first.std::jthread subAlignWorker;QVariantMap prefs;+ // Live recording state published by the engine (see LiveRecorder.h).+ QVariantMap recordingState;// Custom: the display whose HDR curve is currently applied (see syncHdrDisplayProfile).QString hdrProfileDisplay;// Custom: the title whose curve is currently applied (see syncHdrTitleProfile).@@ -1451,6 +1453,26 @@ QmlPlayerBridge::QmlPlayerBridge(engine::EngineController& engine, std::filesystconst auto wasTransport = impl_->snapshot.transport;const uint64_t wasSession = impl_->snapshot.sessionId;if(impl_->poll()){emit settingsChanged();emitChainChanged();}+ // Live recording state: the engine owns the file, this side shows it.+ {+ const auto live=impl_->engine.recordingSnapshot();+ QVariantMap state;+ state["active"]=live.active;+ state["failed"]=live.failed;+ state["path"]=QString::fromStdWString(live.path);+ state["error"]=QString::fromStdWString(live.error);+ state["encoder"]=QString::fromStdWString(live.encoder);+ state["frames"]=QVariant::fromValue(qulonglong(live.frames));+ state["dropped"]=QVariant::fromValue(qulonglong(live.dropped));+ state["seconds"]=live.seconds;+ if(state!=impl_->recordingState){+ const bool wasActive=impl_->recordingState.value("active").toBool();+ impl_->recordingState=state;+ emit recordingChanged();+ if(live.failed&&!live.error.empty())emit notice(uiText(live.error),true);+ else if(wasActive&&!live.active)emit notice(tr("录制已结束:%1").arg(QString::fromStdWString(live.path)),false);+ }+ }// Custom: a display change re-applies that device's HDR curve. The id check is// a few Win32 calls, so this is safe on the polling path.syncHdrDisplayProfile();@@ -6756,8 +6778,12 @@ bool QmlPlayerBridge::setPreference(const QString& key, const QVariant& value) {// 列表模式 parameter panel width (ProPage splitter); QML clamps it to the window.{"listInspectorWidth", {376, 4000}},// Network sources (#48): seconds to collect before the first picture; -1 follows the buffer level.- {"networkPrebuffer", {-1, 60}}};- static const QStringList flags{"subtitleEnabled", "subtitleBackground", "subtitleFit",+ {"networkPrebuffer", {-1, 60}},+ // Live recording: the target bitrate for the file, and the frame rate+ // cap (0 keeps the presented rate).+ {"recordBitrateMbps", {1, 400}},+ {"recordFps", {0, 240}}};+ static const QStringList flags{"recordHevc", "subtitleEnabled", "subtitleBackground", "subtitleFit","subtitleSecondLanguage", "audioForceStereo", "holdCompare","magewellLowLatency", "blackmagicNativeCapture", "captureShowAllFrameRates", "cinePillHidden", "exportStopsPlayback", "obsGameCapture", "autoResume", "fullscreenMemoryProtection", "prewarmEnhancement", "hdrFgCompatibility", "computeOnMonitorGpu", "deinterlace", "networkAutoReconnect"};QVariant stored;@@ -6772,6 +6798,10 @@ bool QmlPlayerBridge::setPreference(const QString& key, const QVariant& value) {const QString dir = value.toString();if (!dir.isEmpty() && !QFileInfo(dir).isDir()) { emit notice(tr("截图目录不存在:%1").arg(dir), true); return false; }stored = dir;+ } else if (key == QLatin1String("recordDir")) {+ const QString dir = value.toString();+ if (!dir.isEmpty() && !QFileInfo(dir).isDir()) { emit notice(tr("录制目录不存在:%1").arg(dir), true); return false; }+ stored = dir;} else if (key == QLatin1String("audioDevice")) {stored = value.toString();} else if (key == QLatin1String("sliderKeyStep")) {@@ -7207,6 +7237,47 @@ void QmlPlayerBridge::openDataFolder() {if (!QDesktopServices::openUrl(QUrl::fromLocalFile(dataDirectory()))) emit notice(tr("无法打开数据目录"), true);}+// --- live recording of the processed picture --------------------------------+// The engine owns the encoder and the file; this side only starts, stops and+// shows the state. The 3 second countdown is an interface animation and runs+// before the request is sent.+QString QmlPlayerBridge::recordingDirectory() const {+ const QString chosen = impl_->prefString("recordDir");+ if (!chosen.isEmpty()) return chosen;+ const QString videos = QStandardPaths::writableLocation(QStandardPaths::MoviesLocation);+ return QDir(videos.isEmpty() ? QDir::homePath() : videos).filePath(QStringLiteral("Veyra"));+}+int QmlPlayerBridge::recordingBitrateMbps() const { return std::clamp(impl_->prefInt("recordBitrateMbps", 20), 1, 400); }+int QmlPlayerBridge::recordingFpsLimit() const { return impl_->prefInt("recordFps", 0); }+bool QmlPlayerBridge::recordingHevc() const { return impl_->prefBool("recordHevc", false); }+bool QmlPlayerBridge::recording() const { return impl_->recordingState.value("active").toBool(); }+QVariantMap QmlPlayerBridge::recordingState() const { return impl_->recordingState; }++void QmlPlayerBridge::startRecording() {+ if (recording()) { emit notice(tr("录制已在进行中"), true); return; }+ if (!hasSource()) { emit notice(tr("没有正在播放的画面,无法录制"), true); return; }+ engine::RecordingOptions options;+ options.directory = wideOf(recordingDirectory());+ options.bitrateMbps = uint32_t(recordingBitrateMbps());+ options.hevc = recordingHevc();+ options.fpsLimit = uint32_t(std::max(0, recordingFpsLimit()));+ impl_->engine.requestRecording(options);+}+void QmlPlayerBridge::stopRecording() {+ if (!recording()) return;+ impl_->engine.stopRecording();+}+void QmlPlayerBridge::toggleRecording() { if (recording()) stopRecording(); else startRecording(); }+void QmlPlayerBridge::chooseRecordingDirectory() {+ const QString dir = QFileDialog::getExistingDirectory(nullptr, tr("选择录制保存位置"), recordingDirectory());+ if (!dir.isEmpty()) setPreference(QStringLiteral("recordDir"), dir);+}+void QmlPlayerBridge::openRecordingDirectory() {+ const QString dir = recordingDirectory();+ QDir().mkpath(dir);+ if (!QDesktopServices::openUrl(QUrl::fromLocalFile(dir))) emit notice(tr("无法打开目录:%1").arg(dir), true);+}+void QmlPlayerBridge::chooseExportPath() {if (impl_->chain.mode == engine::ChainMode::Node) {emit notice(tr("节点链尚未接入导出执行器,请切换列表模式后导出"), true);