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++
checkpoint: preserve Claude unfinished recording repair
Veyra Goal Agent5614e8dfa28b
diff --git a/CMakeLists.txt b/CMakeLists.txtindex 2b6ebc1b..183bec51 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -577,7 +577,9 @@ if(VEYRA_FFMPEG_ROOT AND EXISTS "${VEYRA_FFMPEG_ROOT}/include/libavformat/avformsrc/sink/BitstreamAudioSink.cppsrc/sink/ImageExportSink.cppsrc/sink/NvencD3D12Encoder.cpp+ src/sink/NvencLiveEncoder.cppsrc/sink/MfVideoEncoder.cpp+ src/sink/RecordingAudioTap.cppsrc/sink/VideoEncoderFactory.cpp)veyra_apply_warnings(veyra_sinks)diff --git a/include/veyra/engine/EngineController.h b/include/veyra/engine/EngineController.hindex 750aa433..8b53dff6 100644--- a/include/veyra/engine/EngineController.h+++ b/include/veyra/engine/EngineController.h@@ -250,10 +250,10 @@ 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 RecordingSettings& options);+ // Live recording of the processed picture and the played sound+ // (LiveRecorder.h). Any thread; the file opens with the next presented+ // frame and is finished in the background.+ bool requestRecording(const RecordingSettings& options,std::wstring& error);void stopRecording();RecordingStatus recordingSnapshot()const;private:@@ -262,8 +262,6 @@ private: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);@@ -290,12 +288,9 @@ 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<RecordingSettings> recordingRequest_; // mutex_- bool recordingStop_=false; // mutex_- RecordingStatus recordingStatus_; // mutex_+ // Live recorder: every session's presenter records into it; it owns its+ // encoder and writer threads. Created before the engine thread starts.+ std::unique_ptr<LiveRecorder> recorder_=std::make_unique<LiveRecorder>();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.hindex efeff02c..5db97125 100644--- a/include/veyra/engine/LiveRecorder.h+++ b/include/veyra/engine/LiveRecorder.h@@ -1,74 +1,85 @@#pragma once-// LiveRecorder: records the processed picture the engine presents.+// LiveRecorder: records the processed picture the player presents, with the+// sound it plays.//-// 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>+// Picture: VideoPresenter calls record() inside its presentation command list+// (PresentCapture), so turning the frame into NV12/P010 costs one compute pass+// on the GPU and nothing on the CPU; the engine thread never waits. A frame+// that finds every slot still encoding, or the disk behind, is skipped and+// counted instead of stalling playback. NVENC (NVIDIA) waits for the+// conversion on the GPU; the Media Foundation path (AMD, Intel) reads it back+// on the recorder's own thread.+// Sound: the PCM every renderer plays (sink/RecordingAudioTap.h), before+// volume and mute, timed by when it reaches the endpoint; AAC 48 kHz stereo.+// Gaps become silence and clock drift is absorbed by resampling, so the track+// stays continuous and in sync with the picture.+// File: fragmented MP4, so a crash keeps everything written so far. Settings+// changes keep the file; a change of the output size or HDR mode continues in+// a new file (-2, -3, ...). Files are finished on the recorder's threads.#include <cstdint>#include <memory>-#include <mutex>#include <string>-namespace veyra::gfx { class D3D12DeviceContext; class CommandSlotRing; }-namespace veyra::pipeline { class EnhanceGraph; }+#include "veyra/engine/PresentCapture.h"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+ uint32_t bitrateMbps=0; // 0: automatic from the picture size and frame rate+ bool hevc=false; // H.264 unless chosen; HDR always records HEVC 10-bit+ uint32_t fpsLimit=0; // 0: every presented frame+ bool audio=true; // record the sound the player plays};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+ bool active=false; // recording, or waiting for the first frame+ bool failed=false; // the last recording stopped on an error+ bool finishing=false; // a file is still being finished in the background+ std::wstring path; // the file being written, or the last one finished+ std::wstring error; // why the last recording failed+ std::wstring encoder; // e.g. "NVIDIA NVENC H.264"+ std::wstring note; // stop reason or a new-file note, for the interface+ uint64_t frames=0; // frames encoded since start+ uint64_t dropped=0; // presented frames skipped because the encoder or disk was busy+ double seconds=0; // time since the first recorded frame+ uint32_t files=0; // files this recording wrote (more than one after a size change)+ bool audio=false; // the current file has a sound track+ uint64_t started=0; // +1 per start+ uint64_t saved=0; // +1 per finished file; path is that file while not active};-class LiveRecorder {+class LiveRecorder final : public PresentCapture {public:LiveRecorder();- ~LiveRecorder();- LiveRecorder(const LiveRecorder&) = delete;- LiveRecorder& operator=(const LiveRecorder&) = delete;+ ~LiveRecorder() override;+ 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; }+ // Any thread. Checks the folder; the file opens with the next presented frame.+ bool start(const RecordingSettings& settings,std::wstring& error);+ // Any thread. The file is finished in the background.+ void stop(const std::wstring& note={});+ bool active() const;RecordingStatus status() const;+ // Engine thread: the presented frame rate, used for rate control when+ // every presented frame is recorded.+ void setPresentRateHint(double fps);+ // Engine thread: the session that owns the device ended; so does the recording.+ void sessionEnded(const std::wstring& note);+ // Stops and waits until every file is finished, at most timeoutMs.+ void waitIdle(uint32_t timeoutMs);++ // PresentCapture: engine thread, inside VideoPresenter::present().+ bool record(ID3D12GraphicsCommandList* list,const Frame& frame) override;+ void submitted(ID3D12Fence* fence,uint64_t value) override;+ void discarded() override;+ struct Segment;private:- enum class State { Idle, Recording, Failed };- struct Impl;- std::unique_ptr<Impl> p_;- std::atomic<State> state_{State::Idle};+ struct State;+ std::unique_ptr<State> s_;};} // namespace veyra::enginediff --git a/include/veyra/engine/PresentCapture.h b/include/veyra/engine/PresentCapture.hnew file mode 100644index 00000000..42f12aa0--- /dev/null+++ b/include/veyra/engine/PresentCapture.h@@ -0,0 +1,32 @@+#pragma once+// Live recording (LiveRecorder) reads the presented frame inside the+// presentation command list, after the presenter's own reads. The consumer+// fence the graph waits on before reusing the texture then covers the+// recording too, and no second queue ever touches the graph's textures.+// Engine thread only. Kept free of the presenter's headers: EngineController.h+// is included after Qt, whose `slots` macro breaks diagnostics/GpuTimer.h.+#include <d3d12.h>+#include <cstdint>++namespace veyra::engine {++class PresentCapture {+public:+ struct Frame {+ ID3D12Resource* texture=nullptr; // graph output; COMMON on entry, must be left in COMMON+ DXGI_FORMAT format=DXGI_FORMAT_UNKNOWN;+ uint32_t width=0,height=0;+ uint32_t hdrMode=0; // 0 SDR, 1 scRGB (linear BT.709), 2 HDR10 (PQ BT.2020)+ float ditherStep=0; // graph output dither step (RgbToNv12 reserved.y)+ bool generated=false;+ };+ virtual ~PresentCapture()=default;+ // true: commands were recorded into `list`; submitted() or discarded() follows.+ virtual bool record(ID3D12GraphicsCommandList* list,const Frame& frame)=0;+ // The list was submitted; this fence point covers the recorded commands.+ virtual void submitted(ID3D12Fence* fence,uint64_t value)=0;+ // The list was not submitted (failed present); nothing will execute.+ virtual void discarded()=0;+};++} // namespace veyra::enginediff --git a/include/veyra/engine/VideoPresenter.h b/include/veyra/engine/VideoPresenter.hindex 77587fa1..f847db78 100644--- a/include/veyra/engine/VideoPresenter.h+++ b/include/veyra/engine/VideoPresenter.h@@ -9,6 +9,7 @@#include "veyra/gfx/ReflexSession.h"#include "veyra/gfx/NvidiaVrr.h"#include "veyra/engine/PresentationSettings.h"+#include "veyra/engine/PresentCapture.h"#include <chrono>#include <array>#include <optional>@@ -18,6 +19,8 @@ namespace veyra::sink { struct RgbaImage; }namespace veyra::engine {class VideoPresenter {public:+ // Live recording hook; the object must outlive every present() call.+ void setCapture(PresentCapture* capture){capture_=capture;}~VideoPresenter(){close();}// mediaClockPaced: the owner already waits on a media clock before each// source (file playback). Retained for diagnostics; XeLL low latency must@@ -107,6 +110,7 @@ private:gfx::ReflexSession reflex_;uint64_t reflexFrame_=0,generation_=0;bool providerOwnedPresentation_=false;+ PresentCapture* capture_=nullptr;Microsoft::WRL::ComPtr<ID3D12CommandQueue> presentationQueue_;Microsoft::WRL::ComPtr<ID3D12Fence> presentationFence_;HANDLE presentationEvent_=nullptr;diff --git a/include/veyra/sink/MfLiveEncoder.h b/include/veyra/sink/MfLiveEncoder.hnew file mode 100644index 00000000..690c680b--- /dev/null+++ b/include/veyra/sink/MfLiveEncoder.h@@ -0,0 +1,31 @@+#pragma once+// Media Foundation hardware MFT for the live recorder (AMD and Intel+// adapters, and NVIDIA when NVENC refuses a session): system-memory NV12 in,+// microsecond timestamps in and out, 8-bit 4:2:0 only. The vendor MFT+// selection, rate control and event handling are the export encoder's+// (MfVideoEncoder.cpp). One thread drives every call.+#include <cstdint>+#include <memory>+#include <string>+#include <vector>+#include "veyra/sink/VideoEncoder.h"++namespace veyra::sink {++class MfLiveEncoder {+public:+ virtual ~MfLiveEncoder()=default;+ // config.fpsNum/fpsDen set rate control and the 2 s GOP; the writer+ // receives timestamps in microseconds.+ virtual bool openLive(uint32_t width,uint32_t height,const EncoderConfig& config,PacketWriter writer)=0;+ virtual std::vector<uint8_t> liveHeaders() const=0;+ // Y rows `yPitch` bytes apart, then interleaved UV rows `uvPitch` apart.+ virtual bool encodeNv12(const uint8_t* y,uint32_t yPitch,const uint8_t* uv,uint32_t uvPitch,int64_t ptsUs)=0;+ virtual bool finishLive()=0;+ virtual std::wstring liveDescription() const=0;+ virtual std::wstring liveError() const=0;+};++std::unique_ptr<MfLiveEncoder> createMediaFoundationLiveEncoder();++} // namespace veyra::sinkdiff --git a/include/veyra/sink/NvencLiveEncoder.h b/include/veyra/sink/NvencLiveEncoder.hnew file mode 100644index 00000000..590ad54b--- /dev/null+++ b/include/veyra/sink/NvencLiveEncoder.h@@ -0,0 +1,57 @@+#pragma once+// D3D12 NVENC session for the live recorder. It encodes NV12 (SDR) or P010+// (HDR10) textures the caller owns: each submit names an input texture and+// the caller's fence point after which the texture holds the frame, so NVENC+// waits on the GPU and the caller never blocks. Bitstreams come back in+// submission order. Every call must come from one thread (the recorder's+// encoder thread); open() registers the inputs once for the session.+#include <d3d12.h>+#include <cstdint>+#include <memory>+#include <string>+#include <vector>++namespace veyra::sink {++class NvencLiveEncoder {+public:+ struct Config {+ uint32_t width=0,height=0;+ bool hevc=false;+ bool hdr=false; // HEVC Main10 from P010 inputs, BT.2020 PQ signalling+ uint32_t fps=60; // rate-control frame rate+ uint32_t bitrateMbps=20; // VBR target+ };+ struct Packet {+ std::vector<uint8_t> data;+ int64_t ptsUs=0;+ bool key=false;+ unsigned input=0; // the input texture this frame was read from (free again now)+ };++ NvencLiveEncoder();+ ~NvencLiveEncoder();+ NvencLiveEncoder(const NvencLiveEncoder&)=delete;+ NvencLiveEncoder& operator=(const NvencLiveEncoder&)=delete;++ bool open(ID3D12Device* device,const Config& config,const std::vector<ID3D12Resource*>& inputs);+ // Annex B parameter sets (SPS/PPS, plus VPS for HEVC).+ std::vector<uint8_t> headers() const;+ // Encode input `index` once `fence` reaches `value`. Fails when every+ // output buffer is still pending: take a packet first.+ bool submit(unsigned index,ID3D12Fence* fence,uint64_t value,int64_t ptsUs,bool forceKey=false);+ // The oldest submitted frame. Without `wait`, false when it is still+ // encoding (ready stays false); with it, waits up to timeoutMs.+ bool takeOldest(Packet& packet,bool wait,uint32_t timeoutMs,bool& ready);+ size_t inFlight() const;+ size_t capacity() const;+ void close();+ std::wstring lastError() const;+ std::wstring describe() const;++private:+ struct Impl;+ std::unique_ptr<Impl> p_;+};++} // namespace veyra::sinkdiff --git a/include/veyra/sink/RecordingAudioTap.h b/include/veyra/sink/RecordingAudioTap.hnew file mode 100644index 00000000..bee6dcca--- /dev/null+++ b/include/veyra/sink/RecordingAudioTap.h@@ -0,0 +1,29 @@+#pragma once+// Live recording takes the PCM the player renders - every source that plays+// through AudioRenderer: files, capture-card monitoring, PS5/Moonlight/Xbox+// streaming - before volume and mute, stamped with the steady-clock time at+// which its first frame reaches the endpoint. While no recording takes audio+// the renderer only reads one atomic flag.+#include <cstddef>+#include <cstdint>+#include <memory>+#include "veyra/sink/AudioFormat.h"++namespace veyra::sink {++class RecordingAudioSink {+public:+ virtual ~RecordingAudioSink()=default;+ // Audio owner thread: copy and return, never block. `renderer`+ // identifies the endpoint, so a second renderer can be ignored.+ virtual void renderedPcm(const float* interleaved,size_t frames,const AudioFormat& format,int64_t playoutUs,const void* renderer)=0;+};++// nullptr detaches. Any thread.+void setRecordingAudioSink(std::shared_ptr<RecordingAudioSink> sink);+bool recordingAudioActive();+std::shared_ptr<RecordingAudioSink> recordingAudioSink();+// The clock the recorder stamps video and audio with (steady_clock, µs).+int64_t recordingClockUs();++} // namespace veyra::sinkdiff --git a/include/veyra/sink/WasapiAudioSink.h b/include/veyra/sink/WasapiAudioSink.hindex f9e2a102..547f07d8 100644--- a/include/veyra/sink/WasapiAudioSink.h+++ b/include/veyra/sink/WasapiAudioSink.h@@ -325,6 +325,7 @@ private:std::atomic<bool> fading_{false};bool pausedEndpoint_=false;size_t fadeInRemaining_=0;LiveAudioGapTracker liveGap_;+ int64_t tapLatencyUs_=0; // live recording: device-clock playout minus the queued-frame estimatestd::vector<float> lastRaw_=std::vector<float>(2,0);AudioFormat inputFormat_,outputFormat_;SwrContext* channelMix_=nullptr;diff --git a/include/veyra/ui/QmlPlayerBridge.h b/include/veyra/ui/QmlPlayerBridge.hindex 08b38969..ed677573 100644--- a/include/veyra/ui/QmlPlayerBridge.h+++ b/include/veyra/ui/QmlPlayerBridge.h@@ -227,6 +227,7 @@ class QmlPlayerBridge : public QObject {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(bool recordingAudio READ recordingAudio 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)@@ -1279,6 +1280,7 @@ public:int recordingBitrateMbps() const;int recordingFpsLimit() const;bool recordingHevc() const;+ bool recordingAudio() 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);diff --git a/qml/Veyra/ProPage.qml b/qml/Veyra/ProPage.qmlindex 405a8e34..8b265346 100644--- a/qml/Veyra/ProPage.qml+++ b/qml/Veyra/ProPage.qml@@ -631,6 +631,14 @@ VPage {border.width: 1border.color: (veyra.recording || recordControl.countdown > 0) ? Theme.err : Theme.stroke2property int countdown: 0+ // Elapsed recording time, m:ss (h:mm:ss after an hour).+ readonly property string elapsed: {+ const total = Math.max(0, Math.floor((veyra.recordingState && veyra.recordingState.seconds) || 0))+ const h = Math.floor(total / 3600), m = Math.floor(total / 60) % 60, s = total % 60+ const two = n => (n < 10 ? "0" : "") + n+ return h > 0 ? h + ":" + two(m) + ":" + two(s) : two(m) + ":" + two(s)+ }+ readonly property bool saving: !veyra.recording && !!(veyra.recordingState && veyra.recordingState.finishing)Behavior on color { ColorAnimation { duration: Theme.d(Theme.durFast) } }Behavior on border.color { ColorAnimation { duration: Theme.d(Theme.durFast) } }@@ -654,7 +662,8 @@ VPage {id: recordLabelanchors.verticalCenter: parent.verticalCentertext: recordControl.countdown > 0 ? qsTr("录制 %1 秒").arg(recordControl.countdown)- : (veyra.recording ? qsTr("停止录制") : qsTr("录制"))+ : veyra.recording ? qsTr("停止 %1").arg(recordControl.elapsed)+ : recordControl.saving ? qsTr("保存中…") : qsTr("录制")color: Theme.t1font.family: Theme.fontUifont.pixelSize: Theme.fsBodydiff --git a/qml/Veyra/SettingsPage.qml b/qml/Veyra/SettingsPage.qmlindex b0f400cf..b58c5378 100644--- a/qml/Veyra/SettingsPage.qml+++ b/qml/Veyra/SettingsPage.qml@@ -555,7 +555,7 @@ VPage {objectName: "set-recording"VRow {label: qsTr("录制保存位置")- hint: veyra.recordingDirectory + qsTr("(MP4,只录处理后的画面,不含音频)")+ hint: veyra.recordingDirectory + qsTr("(MP4,录下处理后的画面和正在播放的声音)")RowLayout {spacing: 6VButton { text: qsTr("打开"); ghost: true; onClicked: veyra.openRecordingDirectory() }@@ -564,10 +564,10 @@ VPage {}VRow {label: qsTr("录制码率")- hint: qsTr("目标码率,越高越清晰、文件也越大")+ hint: qsTr("自动按画面尺寸和帧率选择;数字为 Mbps,越高越清晰、文件也越大")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" }]+ options: [{ id: "0", label: qsTr("自动") }, { 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))}@@ -577,14 +577,14 @@ VPage {hint: qsTr("跟随显示可录到补帧后的画面;限速则按该帧率抽帧")VSeg {objectName: "set-recfps"- options: [{ id: "0", label: qsTr("跟随") }, { id: "30", label: "30" }, { id: "60", label: "60" }]+ options: [{ id: "0", label: qsTr("跟随") }, { id: "30", label: "30" }, { id: "60", label: "60" }, { id: "120", label: "120" }]current: String(veyra.recordingFpsLimit)onPicked: id => veyra.setPreference("recordFps", Number(id))}}VRow {label: qsTr("录制编码")- hint: qsTr("HDR 画面固定使用 HEVC 10bit")+ hint: qsTr("HDR 画面固定使用 HEVC 10bit;宽或高超过 4096 时自动使用 HEVC")VSeg {objectName: "set-rechevc"options: [{ id: "0", label: "H.264" }, { id: "1", label: "HEVC" }]@@ -592,6 +592,15 @@ VPage {onPicked: id => veyra.setPreference("recordHevc", id === "1")}}+ VRow {+ label: qsTr("录制声音")+ hint: qsTr("录入播放器正在播放的声音,不受音量和静音影响;采集卡需要开启音频监听")+ VSwitch {+ objectName: "set-recaudio"+ checked: veyra.recordingAudio+ onToggled: v => veyra.setPreference("recordAudio", v)+ }+ }}}VGroup {diff --git a/src/engine/EngineController.cpp b/src/engine/EngineController.cppindex f0c4e767..b787888a 100644--- a/src/engine/EngineController.cpp+++ b/src/engine/EngineController.cpp@@ -366,23 +366,9 @@ 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 RecordingSettings& 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_);recordingStatus_={};return;}- const auto live=recorder_->status();- std::lock_guard lock(mutex_);- recordingStatus_.active=live.active;recordingStatus_.failed=live.failed;- recordingStatus_.path=live.path;recordingStatus_.error=live.error;- recordingStatus_.encoder=live.encoder;recordingStatus_.frames=live.frames;- recordingStatus_.dropped=live.dropped;recordingStatus_.seconds=live.seconds;-}-RecordingStatus EngineController::recordingSnapshot()const{std::lock_guard lock(mutex_);return recordingStatus_;}+bool EngineController::requestRecording(const RecordingSettings& options,std::wstring& error){return recorder_->start(options,error);}+void EngineController::stopRecording(){recorder_->stop();}+RecordingStatus EngineController::recordingSnapshot()const{return recorder_->status();}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");@@ -479,9 +465,8 @@ 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();}+ // A recording belongs to the session (and device) it started in.+ if(recorder_->active())recorder_->sessionEnded(L"已切换播放内容,录制已保存");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:")&&@@ -496,6 +481,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s// only name the stopped command list after the removal, so teardown checks once more.bool gpuFailureAwaitingRemoval=false;sink::AudioPipeline audioPipe;sink::AudioRenderer audio;VideoPresenter presenter;+ presenter.setCapture(recorder_.get());auto& coreCache=gpu->core;auto& recentGraphCache=gpu->recent;auto& graph=gpu->graph;auto& graphBytes=gpu->graphBytes;auto cacheBudgetPolledAt=Clock::now();const bool recentCacheAllowed=!GetEnvironmentVariableW(L"VEYRA_TEST_DISABLE_RECENT_GRAPH_CACHE",nullptr,0);@@ -1201,9 +1187,8 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,sfinishReset(diagnostics::ResetOutcome::Completed);};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();}}};+ // The recording ends with the session; its file is finished in the background.+ recorder_->sessionEnded(stop_?L"播放已停止,录制已保存":L"播放已结束,录制已保存");}};auto collectTimings=[&]{auto record=[&](const diagnostics::GpuFrameTiming& sample){const auto& fgCost=sample.gpu[size_t(diagnostics::GpuStage::FgBatch)];@@ -1559,24 +1544,6 @@ 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<RecordingSettings> 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;@@ -1609,9 +1576,6 @@ 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();@@ -2627,12 +2591,6 @@ 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()));@@ -2795,6 +2753,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,scaptureFlowLast=captureStats;loopTrace.mark("flowUpdate");measured.flow=frameFlow->snapshot(host100ns());+ recorder_->setPresentRateHint(measured.flow.presentSubmitFps);loopTrace.mark("flowSnapshot");measured.sourceFrames=measured.flow.counters.sourceAccepted;measured.validGenerated=measured.flow.counters.fgReadyValid;measured.submitted=measured.flow.counters.realPresented+measured.flow.counters.generatedPresented;measured.expired=measured.flow.counters.generatedExpiredAfterEval;const double ageP95=liveScheduler?completed.ageP95:captureAges.p95(),waitP95=liveScheduler?completed.waitP95:scheduleWaits.p95(),presentP95=liveScheduler?completed.presentP95:presentTimes.p95();diff --git a/src/engine/LiveRecorder.cpp b/src/engine/LiveRecorder.cppindex 5dd53251..d6d2d95d 100644--- a/src/engine/LiveRecorder.cpp+++ b/src/engine/LiveRecorder.cpp@@ -1,338 +1,884 @@#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/pipeline/GpuPassUtils.h"+#include "veyra/sink/MfLiveEncoder.h"+#include "veyra/sink/NvencLiveEncoder.h"+#include "veyra/sink/RecordingAudioTap.h"#include "veyra/Log.h"+#include <dxgi1_6.h>+#include <objbase.h>+#include <wrl/client.h>+#include <algorithm>+#include <array>+#include <atomic>+#include <bit>#include <chrono>+#include <cmath>#include <condition_variable>#include <cstring>#include <ctime>#include <deque>-#include <format>#include <filesystem>+#include <format>+#include <mutex>+#include <optional>#include <thread>#include <vector>extern "C" {-#include <libavformat/avformat.h>#include <libavcodec/avcodec.h>-#include <libavutil/mathematics.h>+#include <libavformat/avformat.h>+#include <libavutil/audio_fifo.h>+#include <libavutil/channel_layout.h>+#include <libavutil/opt.h>+#include <libswresample/swresample.h>}namespace veyra::engine {+using Microsoft::WRL::ComPtr;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);+constexpr unsigned kSlots=6;+constexpr size_t kBacklogSkipBytes=size_t(64)<<20; // the disk is behind: skip frames+constexpr size_t kBacklogFailBytes=size_t(512)<<20; // far behind: stop with an error+constexpr int kAudioRate=48000;+constexpr int64_t kAudioHardGap=kAudioRate*60/1000; // beyond 60 ms: insert silence or drop+constexpr double kAudioSoftGap=kAudioRate*5/1000.0; // beyond 5 ms: resample it away+constexpr int kCompensationWindow=kAudioRate*4; // one soft correction per 4 s+constexpr int kCompensationMax=kCompensationWindow/1000; // at most 0.1 % speed+constexpr size_t kAudioQueueFrames=size_t(kAudioRate)*4;+constexpr uint32_t kGpuWaitMs=3000;++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_t(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);+std::wstring wide(const std::string& text){+ if(text.empty())return {};+ const int size=MultiByteToWideChar(CP_UTF8,0,text.data(),int(text.size()),nullptr,0);+ std::wstring out(size_t(size),L'\0');+ MultiByteToWideChar(CP_UTF8,0,text.data(),int(text.size()),out.data(),size);+ return out;+}+std::wstring avError(int code){char buffer[AV_ERROR_MAX_STRING_SIZE]{};av_strerror(code,buffer,sizeof(buffer));return wide(buffer);}+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);+ 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;}+// About 0.15 bit per pixel for H.264 at the recorded rate; HEVC needs ~2/3 of it.+uint32_t autoBitrateMbps(uint32_t width,uint32_t height,uint32_t fps,bool hevc){+ const double mbps=double(width)*height*fps*0.15*(hevc?0.65:1.0)/1e6;+ return uint32_t(std::clamp<long>(std::lround(mbps),hevc?5:6,hevc?120:150));+}+uint32_t adapterVendor(ID3D12Device* device){+ ComPtr<IDXGIFactory4> factory;+ if(FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory))))return 0;+ ComPtr<IDXGIAdapter1> adapter;+ if(FAILED(factory->EnumAdapterByLuid(device->GetAdapterLuid(),IID_PPV_ARGS(&adapter))))return 0;+ DXGI_ADAPTER_DESC1 desc{};+ return SUCCEEDED(adapter->GetDesc1(&desc))?desc.VendorId:0;+}} // namespace-struct LiveRecorder::Impl {- struct Packet {- std::vector<uint8_t> data;- int64_t ptsUs = 0;- int64_t durationUs = 0;- bool key = false;+// One output file: the capture slots and conversion (engine thread), the+// encoder thread and the writer thread. Created by record() on the engine+// thread; LiveRecorder keeps it until both threads are done.+struct LiveRecorder::Segment final : sink::RecordingAudioSink {+ // Fixed at creation.+ ComPtr<ID3D12Device> device;+ uint32_t width=0,height=0,hdrMode=0,fps=60,bitrateMbps=20,vendor=0;+ bool hevc=false,nvenc=false,audio=false;+ std::wstring path;++ // Engine thread: conversion into the slots.+ pipeline::ComputePass convert;+ pipeline::DescriptorStager stager;+ pipeline::StateTracker states;+ ComPtr<ID3D12Resource> y,uv;+ struct Slot {+ ComPtr<ID3D12Resource> nv12; // NVENC input+ ComPtr<ID3D12Resource> yRead,uvRead; // Media Foundation readback+ UINT yPitch=0,uvPitch=0;+ std::atomic<int> state{0}; // 0 free, 1 recorded, 2 queued for the encoder+ ComPtr<ID3D12Fence> fence; // the presenter's fence; kept alive past the session+ uint64_t value=0;+ int64_t ptsUs=0;};+ std::array<Slot,kSlots> slots;+ int pending=-1;+ std::atomic<int64_t> t0Us{0}; // recording clock of the first frame+ int64_t lastPtsUs=-1;+ std::atomic<uint64_t> frames{0},dropped{0};- // 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+ // Encoder thread.+ std::thread encoderThread;+ std::mutex jobMutex;+ std::condition_variable jobCv;+ std::deque<unsigned> jobs;+ bool jobsClosed=false;+ std::atomic<bool> encoderReady{false};- std::unique_ptr<sink::VideoEncoder> encoder;- AVFormatContext* mux = nullptr;- AVStream* stream = nullptr;- std::thread writer;+ // Writer thread.+ std::thread writerThread;+ struct VideoPacket {std::vector<uint8_t> data;int64_t ptsUs=0;bool key=false;};+ std::mutex outMutex;+ std::condition_variable outCv;+ std::deque<VideoPacket> videoPackets;+ std::vector<uint8_t> headers;+ bool headersReady=false,encoderDone=false;+ std::atomic<size_t> backlogBytes{0};+ std::atomic<int64_t> endUs{-1};+ std::atomic<uint64_t> videoWritten{0};+ std::atomic<int64_t> writtenUs{0};- std::mutex queueMutex;- std::condition_variable queueSignal;- std::deque<Packet> queue;- bool writerStop = false;- std::atomic<bool> writerFailed{false};- std::atomic<bool> headerWritten{false};+ // Audio tap -> writer.+ struct AudioBlock {std::vector<float> pcm;size_t frames=0;sink::AudioFormat format;int64_t playoutUs=0;};+ std::mutex audioMutex;+ std::deque<AudioBlock> audioBlocks;+ size_t audioQueued=0;+ const void* audioRenderer=nullptr;+ int64_t audioRendererUs=0;+ std::atomic<int64_t> audioArrivalUs{0};+ std::atomic<uint64_t> audioGaps{0},audioOverflow{0};- 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: {}", utf8(error)));- }-- 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;+ // Writer-owned FFmpeg state.+ AVFormatContext* mux=nullptr;+ AVStream* videoStream=nullptr;+ AVStream* audioStream=nullptr;+ AVCodecContext* audioCodec=nullptr;+ SwrContext* swr=nullptr;+ sink::AudioFormat swrFormat;+ AVAudioFifo* fifo=nullptr;+ AVFrame* audioFrame=nullptr;+ std::vector<float> planes[2];+ std::vector<float> silence;+ int64_t produced=0,encodedSamples=0,compensationEnd=0,lastVideoDts=INT64_MIN;+ double driftEma=0;+ bool headerWritten=false,audioAligned=false;++ // Shared state.+ std::atomic<bool> closing{false},failed{false},encoderFinished{false},writerFinished{false};+ mutable std::mutex textMutex;+ std::wstring error,encoderName,note;++ ~Segment() override {+ if(encoderThread.joinable())encoderThread.join();+ if(writerThread.joinable())writerThread.join();+ releaseMux();+ }++ bool done() const {return encoderFinished.load()&&writerFinished.load();}+ void join(){if(encoderThread.joinable())encoderThread.join();if(writerThread.joinable())writerThread.join();}+ std::wstring errorText() const {std::lock_guard lock(textMutex);return error;}+ std::wstring encoderText() const {std::lock_guard lock(textMutex);return encoderName;}+ std::wstring noteText() const {std::lock_guard lock(textMutex);return note;}+ void setNote(std::wstring text){std::lock_guard lock(textMutex);note=std::move(text);}++ void fail(const std::wstring& reason){+ {std::lock_guard lock(textMutex);if(error.empty())error=reason;}+ if(!failed.exchange(true))veyra::log::error("live-recorder",std::format("segment failed path={} reason={}",utf8(path),utf8(reason)));+ closeJobs();+ }+ void closeJobs(){+ closing=true;+ {std::lock_guard lock(jobMutex);jobsClosed=true;}+ jobCv.notify_all();+ }+ // Any thread: no more frames; the threads finish the file.+ void finish(int64_t endClockUs){+ const int64_t t0=t0Us.load();+ if(t0&&endUs.load()<0)endUs=std::max<int64_t>(0,endClockUs-t0);+ closeJobs();+ }+ bool matches(const PresentCapture::Frame& frame) const {+ return frame.width==width&&frame.height==height&&frame.hdrMode==hdrMode;+ }++ // ---- creation (engine thread) -------------------------------------------+ bool create(std::wstring& reason){+ std::vector<uint8_t> shader;+ if(!convert.loadShader("RgbToNv12.dxil",shader)||!convert.create(device.Get(),shader,kSlots+2,1,2)){reason=L"录制转换着色器加载失败";return false;}+ if(!stager.initialize(device.Get(),kSlots)){reason=L"录制描述符分配失败";return false;}+ const bool hdr=hdrMode!=0;+ y=pipeline::makeTexture(device.Get(),width,height,hdr?DXGI_FORMAT_R16_UNORM:DXGI_FORMAT_R8_UNORM,true);+ uv=pipeline::makeTexture(device.Get(),width/2,height/2,hdr?DXGI_FORMAT_R16G16_UNORM:DXGI_FORMAT_R8G8_UNORM,true);+ if(!y||!uv){reason=L"录制显存分配失败";return false;}+ pipeline::makeUav(device.Get(),y.Get(),hdr?DXGI_FORMAT_R16_UNORM:DXGI_FORMAT_R8_UNORM,pipeline::cpuHandleOf(convert,kSlots));+ pipeline::makeUav(device.Get(),uv.Get(),hdr?DXGI_FORMAT_R16G16_UNORM:DXGI_FORMAT_R8G8_UNORM,pipeline::cpuHandleOf(convert,kSlots+1));+ for(auto& slot:slots){+ if(nvenc){+ slot.nv12=pipeline::makeTexture(device.Get(),width,height,hdr?DXGI_FORMAT_P010:DXGI_FORMAT_NV12,false);+ if(!slot.nv12){reason=L"录制显存分配失败";return false;}+ continue;+ }+ auto readback=[&](UINT rowBytes,UINT rows,ComPtr<ID3D12Resource>& out,UINT& pitch){+ pitch=(rowBytes+255)/256*256;+ D3D12_HEAP_PROPERTIES hp{};hp.Type=D3D12_HEAP_TYPE_READBACK;+ D3D12_RESOURCE_DESC bd{};bd.Dimension=D3D12_RESOURCE_DIMENSION_BUFFER;bd.Width=uint64_t(pitch)*rows;bd.Height=1;+ bd.DepthOrArraySize=1;bd.MipLevels=1;bd.SampleDesc.Count=1;bd.Layout=D3D12_TEXTURE_LAYOUT_ROW_MAJOR;+ return SUCCEEDED(device->CreateCommittedResource(&hp,D3D12_HEAP_FLAG_NONE,&bd,D3D12_RESOURCE_STATE_COPY_DEST,nullptr,IID_PPV_ARGS(&out)));+ };+ if(!readback(width,height,slot.yRead,slot.yPitch)||!readback(width,height/2,slot.uvRead,slot.uvPitch)){reason=L"录制回读缓冲分配失败";return false;}}- av_packet_free(&raw);- return ok;+ encoderThread=std::thread([this]{encoderMain();});+ writerThread=std::thread([this]{writerMain();});+ return true;}- 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;+ // ---- capture (engine thread) ---------------------------------------------+ bool capture(ID3D12GraphicsCommandList* list,const PresentCapture::Frame& frame,int64_t nowUs){+ if(closing.load()||!encoderReady.load())return false;+ if(backlogBytes.load()>=kBacklogFailBytes){fail(L"磁盘写入跟不上录制,已停止录制(请换更快的磁盘或降低码率)");return false;}+ if(backlogBytes.load()>=kBacklogSkipBytes){++dropped;return false;}+ int index=-1;+ for(unsigned i=0;i<kSlots;++i){int expected=0;if(slots[i].state.compare_exchange_strong(expected,1)){index=int(i);break;}}+ if(index<0){++dropped;return false;}+ auto& slot=slots[size_t(index)];+ if(!t0Us.load())t0Us=nowUs;+ int64_t pts=nowUs-t0Us.load();+ if(pts<=lastPtsUs)pts=lastPtsUs+1;+ lastPtsUs=pts;slot.ptsUs=pts;+ // Per-frame SRV through the staging heap (GpuPassUtils.h driver note:+ // a direct SRV write into a shader-visible heap can corrupt Present).+ D3D12_SHADER_RESOURCE_VIEW_DESC view{};view.Format=frame.format;view.ViewDimension=D3D12_SRV_DIMENSION_TEXTURE2D;+ view.Shader4ComponentMapping=D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;view.Texture2D.MipLevels=1;+ stager.stageSrv(frame.texture,&view,convert.heap.Get(),UINT(index));+ D3D12_RESOURCE_BARRIER source{};source.Type=D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;source.Transition.pResource=frame.texture;+ source.Transition.Subresource=D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;+ source.Transition.StateBefore=D3D12_RESOURCE_STATE_COMMON;source.Transition.StateAfter=D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE;+ list->ResourceBarrier(1,&source);+ states.transition(list,y.Get(),D3D12_RESOURCE_STATE_UNORDERED_ACCESS);+ states.transition(list,uv.Get(),D3D12_RESOURCE_STATE_UNORDERED_ACCESS);+ // reserved.x = HDR mode, reserved.y = output dither step (RgbToNv12.hlsl).+ const float constants[8]={std::bit_cast<float>(width),std::bit_cast<float>(height),std::bit_cast<float>(hdrMode),frame.ditherStep,0,0,0,0};+ convert.bind(list,constants,pipeline::gpuHandleOf(convert,UINT(index)).ptr,pipeline::gpuHandleOf(convert,kSlots).ptr);+ list->Dispatch((width+15)/16,(height+15)/16,1);+ states.uavBarrier(list,y.Get());states.uavBarrier(list,uv.Get());+ states.transition(list,y.Get(),D3D12_RESOURCE_STATE_COPY_SOURCE);+ states.transition(list,uv.Get(),D3D12_RESOURCE_STATE_COPY_SOURCE);+ std::swap(source.Transition.StateBefore,source.Transition.StateAfter);+ list->ResourceBarrier(1,&source);+ if(nvenc){+ D3D12_RESOURCE_BARRIER target{};target.Type=D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;target.Transition.pResource=slot.nv12.Get();+ target.Transition.Subresource=D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;+ target.Transition.StateBefore=D3D12_RESOURCE_STATE_COMMON;target.Transition.StateAfter=D3D12_RESOURCE_STATE_COPY_DEST;+ list->ResourceBarrier(1,&target);+ for(UINT plane=0;plane<2;++plane){+ D3D12_TEXTURE_COPY_LOCATION from{},to{};+ from.pResource=plane?uv.Get():y.Get();from.Type=D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;from.SubresourceIndex=0;+ to.pResource=slot.nv12.Get();to.Type=D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;to.SubresourceIndex=plane;+ list->CopyTextureRegion(&to,0,0,0,&from,nullptr);+ }+ std::swap(target.Transition.StateBefore,target.Transition.StateAfter);+ list->ResourceBarrier(1,&target);+ }else{+ auto copyPlane=[&](ID3D12Resource* from,ID3D12Resource* to,DXGI_FORMAT format,UINT w,UINT h,UINT pitch){+ D3D12_TEXTURE_COPY_LOCATION a{},b{};+ a.pResource=from;a.Type=D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;a.SubresourceIndex=0;+ b.pResource=to;b.Type=D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;+ b.PlacedFootprint.Footprint.Format=format;b.PlacedFootprint.Footprint.Width=w;b.PlacedFootprint.Footprint.Height=h;+ b.PlacedFootprint.Footprint.Depth=1;b.PlacedFootprint.Footprint.RowPitch=pitch;+ list->CopyTextureRegion(&b,0,0,0,&a,nullptr);+ };+ copyPlane(y.Get(),slot.yRead.Get(),DXGI_FORMAT_R8_UNORM,width,height,slot.yPitch);+ copyPlane(uv.Get(),slot.uvRead.Get(),DXGI_FORMAT_R8G8_UNORM,width/2,height/2,slot.uvPitch);}- headerWritten.store(true, std::memory_order_relaxed);- veyra::log::info("live-recorder", std::format("container header written path={}", utf8(path)));- for (;;) {- Packet packet;+ pending=index;+ return true;+ }+ void submittedPending(ID3D12Fence* fence,uint64_t value){+ if(pending<0)return;+ auto& slot=slots[size_t(pending)];pending=-1;+ slot.fence=fence;slot.value=value;slot.state=2;+ {std::lock_guard lock(jobMutex);jobs.push_back(unsigned(&slot-slots.data()));}+ jobCv.notify_one();+ ++frames;+ }+ void discardPending(){+ if(pending<0)return;+ slots[size_t(pending)].state=0;pending=-1;+ }+ void releaseSlot(unsigned index){slots[index].fence.Reset();slots[index].state=0;}++ // ---- encoder thread -------------------------------------------------------+ void publishHeaders(std::vector<uint8_t> bytes,std::wstring name){+ {std::lock_guard lock(textMutex);encoderName=std::move(name);}+ {std::lock_guard lock(outMutex);headers=std::move(bytes);headersReady=true;}+ outCv.notify_all();+ encoderReady=true;+ }+ void pushVideo(std::vector<uint8_t> data,int64_t ptsUs,bool key){+ const size_t size=data.size();+ {std::lock_guard lock(outMutex);videoPackets.push_back({std::move(data),ptsUs,key});}+ backlogBytes+=size;+ outCv.notify_one();+ }+ void encoderMain(){+ if(nvenc)encodeNvenc();else encodeMediaFoundation();+ encoderReady=false;closing=true;+ for(unsigned i=0;i<kSlots;++i)if(slots[i].state.load()==2)releaseSlot(i);+ {std::lock_guard lock(outMutex);encoderDone=true;}+ outCv.notify_all();+ encoderFinished=true;+ }+ void encodeNvenc(){+ sink::NvencLiveEncoder encoder;+ sink::NvencLiveEncoder::Config config;+ config.width=width;config.height=height;config.hevc=hevc;config.hdr=hdrMode!=0;config.fps=fps;config.bitrateMbps=bitrateMbps;+ std::vector<ID3D12Resource*> inputs;for(auto& slot:slots)inputs.push_back(slot.nv12.Get());+ if(!encoder.open(device.Get(),config,inputs)){fail(L"NVENC 无法开始录制:"+encoder.lastError());return;}+ publishHeaders(encoder.headers(),encoder.describe());+ veyra::log::info("live-recorder",std::format("encoder ready {} path={}",utf8(encoder.describe()),utf8(path)));+ for(;;){+ std::vector<unsigned> batch;bool closed=false;{- std::unique_lock lock(queueMutex);- queueSignal.wait(lock, [this] { return writerStop || !queue.empty(); });- if (queue.empty()) {- if (writerStop) break;- continue;+ std::unique_lock lock(jobMutex);+ if(jobs.empty()&&!jobsClosed&&encoder.inFlight()==0)jobCv.wait(lock,[&]{return !jobs.empty()||jobsClosed;});+ while(!jobs.empty()&&batch.size()+encoder.inFlight()<encoder.capacity()){batch.push_back(jobs.front());jobs.pop_front();}+ closed=jobsClosed&&jobs.empty();+ }+ for(const auto index:batch){+ auto& slot=slots[index];+ if(!encoder.submit(index,slot.fence.Get(),slot.value,slot.ptsUs)){fail(L"NVENC 编码失败:"+encoder.lastError());break;}+ }+ if(failed.load())break;+ // Hand finished frames to the writer; block on the oldest only+ // when nothing new can be submitted meanwhile.+ bool blocked=false;+ while(encoder.inFlight()){+ bool more=false;{std::lock_guard lock(jobMutex);more=!jobs.empty();}+ const bool wait=!(more&&encoder.inFlight()<encoder.capacity())&&!blocked;+ sink::NvencLiveEncoder::Packet packet;bool ready=false;+ if(!encoder.takeOldest(packet,wait,kGpuWaitMs,ready)){fail(L"NVENC 编码失败:"+encoder.lastError());break;}+ if(!ready)break;+ blocked|=wait;+ releaseSlot(packet.input);+ pushVideo(std::move(packet.data),packet.ptsUs,packet.key);+ }+ if(failed.load())break;+ if(closed&&!encoder.inFlight()){std::lock_guard lock(jobMutex);if(jobs.empty())break;}+ }+ encoder.close();+ }+ void encodeMediaFoundation(){+ const bool com=SUCCEEDED(CoInitializeEx(nullptr,COINIT_MULTITHREADED));+ {+ auto encoder=sink::createMediaFoundationLiveEncoder();+ sink::EncoderConfig config;config.hevc=hevc;config.fpsNum=fps;config.fpsDen=1;config.bitrateMbps=bitrateMbps;+ config.rateControl=sink::ExportRateControl::Vbr;config.adapterVendorId=vendor;config.drainTimeoutMs=kGpuWaitMs;+ auto writer=[this](const uint8_t* bytes,size_t size,int64_t ptsUs,bool key){pushVideo(std::vector<uint8_t>(bytes,bytes+size),ptsUs,key);return true;};+ if(!encoder->openLive(width,height,config,writer)){fail(L"系统硬件编码器无法开始录制:"+encoder->liveError());}+ else{+ publishHeaders(encoder->liveHeaders(),encoder->liveDescription());+ veyra::log::info("live-recorder",std::format("encoder ready {} path={}",utf8(encoder->liveDescription()),utf8(path)));+ HANDLE event=CreateEventW(nullptr,FALSE,FALSE,nullptr);+ for(;;){+ unsigned index=0;+ {+ std::unique_lock lock(jobMutex);+ jobCv.wait(lock,[&]{return !jobs.empty()||jobsClosed;});+ if(jobs.empty())break;+ index=jobs.front();jobs.pop_front();+ }+ auto& slot=slots[index];+ if(slot.fence->GetCompletedValue()<slot.value&&(!event||FAILED(slot.fence->SetEventOnCompletion(slot.value,event))||WaitForSingleObject(event,kGpuWaitMs)!=WAIT_OBJECT_0)){+ fail(L"录制画面回读超时");releaseSlot(index);break;+ }+ void* yData=nullptr;void* uvData=nullptr;+ const D3D12_RANGE yRange{0,size_t(slot.yPitch)*height},uvRange{0,size_t(slot.uvPitch)*(height/2)};+ bool ok=SUCCEEDED(slot.yRead->Map(0,&yRange,&yData))&&SUCCEEDED(slot.uvRead->Map(0,&uvRange,&uvData));+ if(ok)ok=encoder->encodeNv12(static_cast<const uint8_t*>(yData),slot.yPitch,static_cast<const uint8_t*>(uvData),slot.uvPitch,slot.ptsUs);+ const D3D12_RANGE none{0,0};+ if(yData)slot.yRead->Unmap(0,&none);+ if(uvData)slot.uvRead->Unmap(0,&none);+ releaseSlot(index);+ if(!ok){fail(L"系统硬件编码失败:"+encoder->liveError());break;}}- packet = std::move(queue.front());- queue.pop_front();+ if(event)CloseHandle(event);+ if(!failed.load()&&!encoder->finishLive())fail(L"系统硬件编码器收尾失败:"+encoder->liveError());}- 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");+ if(com)CoUninitialize();}-};-LiveRecorder::LiveRecorder() : p_(std::make_unique<Impl>()) {}-LiveRecorder::~LiveRecorder() { end(); }+ // ---- audio tap (audio owner thread) ---------------------------------------+ void renderedPcm(const float* pcm,size_t count,const sink::AudioFormat& format,int64_t playoutUs,const void* renderer) override {+ if(!audio||closing.load()||!format.valid()||!count)return;+ const int64_t now=sink::recordingClockUs();+ std::lock_guard lock(audioMutex);+ // One endpoint at a time; another renderer takes over only after the+ // current one has been quiet for half a second (endpoint rebuilds).+ if(audioRenderer&&audioRenderer!=renderer&&now-audioRendererUs<500000)return;+ audioRenderer=renderer;audioRendererUs=now;audioArrivalUs=now;+ AudioBlock block;block.pcm.assign(pcm,pcm+count*format.channels);block.frames=count;block.format=format;block.playoutUs=playoutUs;+ audioQueued+=count;audioBlocks.push_back(std::move(block));+ while(audioQueued>kAudioQueueFrames&&!audioBlocks.empty()){audioQueued-=audioBlocks.front().frames;audioBlocks.pop_front();++audioOverflow;}+ }-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;+ // ---- writer thread ---------------------------------------------------------+ void releaseMux(){+ if(mux){+ if(mux->pb)avio_closep(&mux->pb);+ avformat_free_context(mux);mux=nullptr;+ }+ if(audioCodec)avcodec_free_context(&audioCodec);+ if(swr)swr_free(&swr);+ if(fifo){av_audio_fifo_free(fifo);fifo=nullptr;}+ if(audioFrame)av_frame_free(&audioFrame);+ }+ bool openFile(std::vector<uint8_t> extradata){+ if(avformat_alloc_output_context2(&mux,nullptr,"mp4",nullptr)<0||!mux){fail(L"无法创建录制封装器");return false;}+ videoStream=avformat_new_stream(mux,nullptr);+ if(!videoStream){fail(L"无法创建录制视频流");return false;}+ videoStream->time_base=AVRational{1,1000000};+ videoStream->avg_frame_rate=AVRational{int(fps),1};+ auto* par=videoStream->codecpar;+ const bool hdr=hdrMode!=0;+ par->codec_type=AVMEDIA_TYPE_VIDEO;par->codec_id=hevc?AV_CODEC_ID_HEVC:AV_CODEC_ID_H264;+ par->width=int(width);par->height=int(height);+ par->format=hdr?AV_PIX_FMT_YUV420P10LE:AV_PIX_FMT_YUV420P;+ par->color_range=AVCOL_RANGE_MPEG;+ par->color_space=hdr?AVCOL_SPC_BT2020_NCL:AVCOL_SPC_BT709;+ par->color_primaries=hdr?AVCOL_PRI_BT2020:AVCOL_PRI_BT709;+ par->color_trc=hdr?AVCOL_TRC_SMPTE2084:AVCOL_TRC_BT709;+ if(hdr)par->profile=AV_PROFILE_HEVC_MAIN_10;+ par->extradata=static_cast<uint8_t*>(av_mallocz(extradata.size()+AV_INPUT_BUFFER_PADDING_SIZE));+ if(!par->extradata){fail(L"无法写入录制文件头");return false;}+ std::memcpy(par->extradata,extradata.data(),extradata.size());par->extradata_size=int(extradata.size());+ if(audio&&!openAudio()){+ audio=false;+ setNote(L"没有可用的 AAC 编码器,本次录制不含声音");+ veyra::log::warn("live-recorder","AAC encoder unavailable; recording without sound");+ }+ int rc=avio_open(&mux->pb,utf8(path).c_str(),AVIO_FLAG_WRITE);+ if(rc<0){fail(L"无法创建录制文件:"+avError(rc));return false;}+ // Fragmented MP4: every fragment is playable on its own, so an+ // interrupted recording keeps what was written.+ AVDictionary* options=nullptr;+ av_dict_set(&options,"movflags","frag_keyframe+empty_moov+default_base_moof",0);+ rc=avformat_write_header(mux,&options);+ av_dict_free(&options);+ if(rc<0){fail(L"无法写入录制文件头:"+avError(rc));return false;}+ headerWritten=true;+ veyra::log::info("live-recorder",std::format("file open path={} extent={}x{} codec={} hdr={} fps={} bitrateMbps={} audio={}",+ utf8(path),width,height,hevc?"HEVC":"H264",hdrMode,fps,bitrateMbps,audio));+ return true;+ }+ bool openAudio(){+ const AVCodec* codec=avcodec_find_encoder(AV_CODEC_ID_AAC);+ if(!codec)return false;+ audioCodec=avcodec_alloc_context3(codec);+ if(!audioCodec)return false;+ audioCodec->sample_fmt=AV_SAMPLE_FMT_FLTP;audioCodec->sample_rate=kAudioRate;+ const AVChannelLayout stereo=AV_CHANNEL_LAYOUT_STEREO;+ av_channel_layout_copy(&audioCodec->ch_layout,&stereo);+ audioCodec->bit_rate=192000;audioCodec->time_base=AVRational{1,kAudioRate};+ if(mux->oformat->flags&AVFMT_GLOBALHEADER)audioCodec->flags|=AV_CODEC_FLAG_GLOBAL_HEADER;+ if(avcodec_open2(audioCodec,codec,nullptr)<0){avcodec_free_context(&audioCodec);return false;}+ fifo=av_audio_fifo_alloc(AV_SAMPLE_FMT_FLTP,2,kAudioRate);+ audioFrame=av_frame_alloc();+ if(!fifo||!audioFrame)return false;+ audioFrame->nb_samples=audioFrameSize();+ audioFrame->format=AV_SAMPLE_FMT_FLTP;audioFrame->sample_rate=kAudioRate;+ av_channel_layout_copy(&audioFrame->ch_layout,&stereo);+ if(av_frame_get_buffer(audioFrame,0)<0)return false;+ audioStream=avformat_new_stream(mux,nullptr);+ if(!audioStream||avcodec_parameters_from_context(audioStream->codecpar,audioCodec)<0)return false;+ audioStream->time_base=AVRational{1,kAudioRate};+ return true;+ }+ int audioFrameSize() const {return audioCodec&&audioCodec->frame_size>0?audioCodec->frame_size:1024;}+ bool writeVideo(const VideoPacket& packet,int64_t durationUs){+ AVPacket* out=av_packet_alloc();+ if(!out||av_new_packet(out,int(packet.data.size()))<0){av_packet_free(&out);return false;}+ std::memcpy(out->data,packet.data.data(),packet.data.size());+ out->stream_index=videoStream->index;out->pts=out->dts=packet.ptsUs;out->duration=std::max<int64_t>(1,durationUs);+ if(packet.key)out->flags|=AV_PKT_FLAG_KEY;+ av_packet_rescale_ts(out,AVRational{1,1000000},videoStream->time_base);+ if(out->dts<=lastVideoDts)out->pts=out->dts=lastVideoDts+1;+ lastVideoDts=out->dts;+ const int rc=av_interleaved_write_frame(mux,out);+ av_packet_free(&out);+ if(rc<0){veyra::log::error("live-recorder",std::format("video write failed rc={}",rc));return false;}+ ++videoWritten;writtenUs=packet.ptsUs;+ return true;+ }+ bool sendAudio(AVFrame* frame){+ if(avcodec_send_frame(audioCodec,frame)<0)return false;+ AVPacket* packet=av_packet_alloc();+ if(!packet)return false;+ int rc=0;+ while((rc=avcodec_receive_packet(audioCodec,packet))>=0){+ packet->stream_index=audioStream->index;+ av_packet_rescale_ts(packet,audioCodec->time_base,audioStream->time_base);+ if(av_interleaved_write_frame(mux,packet)<0){av_packet_free(&packet);return false;}+ }+ av_packet_free(&packet);+ return rc==AVERROR(EAGAIN)||rc==AVERROR_EOF;+ }+ bool configureSwr(const sink::AudioFormat& format){+ if(swr&&format==swrFormat)return true;+ if(swr){+ // Rare: the source layout changed. Keep what the old one buffered.+ if(!convertPcm(nullptr,0))return false;+ swr_free(&swr);+ }+ AVChannelLayout in{};+ if(av_channel_layout_from_mask(&in,format.mask)<0||in.nb_channels!=int(format.channels)){+ av_channel_layout_uninit(&in);av_channel_layout_default(&in,int(format.channels));+ }+ const AVChannelLayout out=AV_CHANNEL_LAYOUT_STEREO;+ int rc=swr_alloc_set_opts2(&swr,&out,AV_SAMPLE_FMT_FLTP,kAudioRate,&in,AV_SAMPLE_FMT_FLT,kAudioRate,0,nullptr);+ av_channel_layout_uninit(&in);+ if(rc<0||!swr)return false;+ // The resampler at an equal rate is what lets swr_set_compensation+ // absorb the endpoint clock's drift against the recording clock.+ av_opt_set_int(swr,"flags",SWR_FLAG_RESAMPLE,0);+ if(swr_init(swr)<0){swr_free(&swr);return false;}+ swrFormat=format;compensationEnd=produced;+ silence.assign(size_t(kAudioRate/10)*format.channels,0.0f);+ return true;+ }+ bool convertPcm(const float* pcm,int count){+ const int capacity=swr_get_out_samples(swr,count)+32;+ if(capacity<=0)return true;+ for(auto& plane:planes)if(plane.size()<size_t(capacity))plane.resize(size_t(capacity));+ uint8_t* out[2]={reinterpret_cast<uint8_t*>(planes[0].data()),reinterpret_cast<uint8_t*>(planes[1].data())};+ const uint8_t* in[1]={reinterpret_cast<const uint8_t*>(pcm)};+ const int got=swr_convert(swr,out,capacity,pcm?in:nullptr,pcm?count:0);+ if(got<0)return false;+ if(got>0){+ void* data[2]={planes[0].data(),planes[1].data()};+ if(av_audio_fifo_write(fifo,data,got)<got)return false;+ produced+=got;+ }+ return true;+ }+ bool feedSilence(int64_t count){+ const int64_t chunk=int64_t(silence.size()/swrFormat.channels);+ while(count>0){+ const int n=int(std::min(count,chunk));+ if(!convertPcm(silence.data(),n))return false;+ count-=n;+ }+ return true;+ }+ int64_t outputPosition() const {return produced+(swr?swr_get_delay(swr,kAudioRate):0);}+ // The final pass encodes up to `limit` samples (the picture's end) and+ // discards anything the resampler produced beyond it.+ bool encodeFifo(bool final,int64_t limit=INT64_MAX){+ const int frameSize=audioFrameSize();+ for(;;){+ int64_t available=av_audio_fifo_size(fifo);+ if(final)available=std::min(available,limit-encodedSamples);+ if(available<=0||(!final&&available<frameSize))break;+ const int n=int(std::min<int64_t>(available,frameSize));+ if(av_frame_make_writable(audioFrame)<0)return false;+ audioFrame->nb_samples=n;+ if(av_audio_fifo_read(fifo,reinterpret_cast<void**>(audioFrame->data),n)<n)return false;+ audioFrame->pts=encodedSamples;encodedSamples+=n;+ if(!sendAudio(audioFrame))return false;+ audioFrame->nb_samples=frameSize;+ }+ if(!final)return true;+ if(av_audio_fifo_size(fifo)>0)av_audio_fifo_drain(fifo,av_audio_fifo_size(fifo));+ return sendAudio(nullptr);+ }+ bool processAudio(bool final,int64_t endTimeUs){+ std::deque<AudioBlock> blocks;+ {std::lock_guard lock(audioMutex);blocks.swap(audioBlocks);audioQueued=0;}+ const int64_t t0=t0Us.load();+ if(!t0)return true; // nothing recorded yet: earlier sound is not part of the file+ if(!swr&&!configureSwr(blocks.empty()?sink::AudioFormat{}:blocks.front().format))return false;+ for(auto& block:blocks){+ if(!configureSwr(block.format))return false;+ int64_t start=(block.playoutUs-t0)*kAudioRate/1000000;+ size_t offset=0;+ if(start<0){const auto trim=size_t(-start);if(trim>=block.frames)continue;offset=trim;start=0;}+ int64_t drift=start-outputPosition();+ // The first block is placed exactly; later ones only beyond the+ // hard limit (gaps, rebuffering) - smaller drift is resampled away.+ const bool align=!audioAligned||drift>kAudioHardGap||drift< -kAudioHardGap;+ if(align&&drift>0){if(!feedSilence(drift))return false;if(audioAligned)++audioGaps;drift=0;}+ else if(align&&drift<0){const auto trim=size_t(-drift);if(trim>=block.frames-offset)continue;offset+=trim;drift=0;}+ audioAligned=true;+ driftEma=driftEma*0.9+double(drift)*0.1;+ if(std::abs(driftEma)>kAudioSoftGap&&produced>=compensationEnd){+ const int delta=int(std::clamp(driftEma,-double(kCompensationMax),double(kCompensationMax)));+ if(delta&&swr_set_compensation(swr,delta,kCompensationWindow)>=0)compensationEnd=produced+kCompensationWindow;+ }+ if(!convertPcm(block.pcm.data()+offset*block.format.channels,int(block.frames-offset)))return false;+ }+ if(final){+ const int64_t target=endTimeUs*kAudioRate/1000000;+ if(target>outputPosition()&&!feedSilence(target-outputPosition()))return false;+ if(!convertPcm(nullptr,0))return false;+ // Exactly as long as the picture.+ return encodeFifo(true,std::max<int64_t>(target,0));+ }else if(blocks.empty()&&sink::recordingClockUs()-std::max(audioArrivalUs.load(),t0)>300000){+ // No sound reaches the endpoint (paused, muted source, no audio+ // monitoring): keep the track continuous, 200 ms behind real time.+ const int64_t target=(sink::recordingClockUs()-t0-200000)*kAudioRate/1000000;+ if(target>outputPosition()&&!feedSilence(target-outputPosition()))return false;+ }+ return encodeFifo(final);+ }+ void writerMain(){+ std::vector<uint8_t> extradata;{- 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+ std::unique_lock lock(outMutex);+ outCv.wait(lock,[&]{return headersReady||encoderDone;});+ if(headersReady)extradata=headers;+ }+ bool ok=!extradata.empty()&&openFile(std::move(extradata));+ std::optional<VideoPacket> held;+ const int64_t frameUs=1000000/std::max(1u,fps);+ while(ok){+ std::deque<VideoPacket> batch;bool ended=false;+ {+ std::unique_lock lock(outMutex);+ outCv.wait_for(lock,std::chrono::milliseconds(20),[&]{return !videoPackets.empty()||encoderDone;});+ batch.swap(videoPackets);+ ended=encoderDone;}- p_->queue.push_back(std::move(packet));+ for(auto& packet:batch){+ backlogBytes-=packet.data.size();+ if(ok&&held)ok=writeVideo(*held,packet.ptsUs-held->ptsUs);+ held=std::move(packet);+ }+ if(ok&&audio)ok=processAudio(false,0);+ if(!ok){fail(L"写入录制文件失败(磁盘已满或没有写入权限?)");break;}+ if(ended)break;}- p_->queueSignal.notify_one();- return true;- };+ // Drop what can no longer be written.+ {std::lock_guard lock(outMutex);for(auto& packet:videoPackets)backlogBytes-=packet.data.size();videoPackets.clear();}+ if(headerWritten){+ int64_t end=endUs.load();+ if(held)end=std::max(end,held->ptsUs+frameUs);+ if(ok&&held)ok=writeVideo(*held,end-held->ptsUs);+ if(ok&&audio&&videoWritten.load())ok=processAudio(true,end);+ const int rc=av_write_trailer(mux);+ if(rc<0)ok=false;+ if(!ok&&!failed.load())fail(L"录制文件收尾失败");+ avio_closep(&mux->pb);+ if(!videoWritten.load()){+ std::error_code code;std::filesystem::remove(path,code);+ setNote(L"没有录到画面,未保存文件");+ }+ veyra::log::info("live-recorder",std::format("file closed path={} videoFrames={} seconds={:.2f} audio={} audioGaps={} audioOverflow={} dropped={} ok={}",+ utf8(path),videoWritten.load(),double(end)/1e6,audio,audioGaps.load(),audioOverflow.load(),dropped.load(),ok));+ }+ releaseMux();+ writerFinished=true;+ }+};++struct LiveRecorder::State {+ mutable std::mutex m;+ RecordingSettings settings;+ bool armed=false;+ std::shared_ptr<Segment> current,pendingCapture;+ std::vector<std::shared_ptr<Segment>> finishing;+ std::wstring baseName;+ unsigned nextNumber=1;+ int64_t firstFrameUs=0,nextDueUs=0;+ double lastSeconds=0;+ std::atomic<double> presentFps{0};+ bool failed=false;+ std::wstring path,error,encoder,note;+ uint64_t framesBase=0,droppedBase=0;+ uint32_t files=0;+ uint64_t started=0,saved=0;+ bool audioTrack=false;++ void retire(const std::shared_ptr<Segment>& segment,const std::wstring& why){+ if(!segment)return;+ if(sink::recordingAudioSink().get()==segment.get())sink::setRecordingAudioSink(nullptr);+ if(!why.empty()&&segment->noteText().empty())segment->setNote(why);+ if(const auto name=segment->encoderText();!name.empty())encoder=name;+ segment->finish(sink::recordingClockUs());+ framesBase+=segment->frames.load();droppedBase+=segment->dropped.load();+ finishing.push_back(segment);+ }+ void reap(){+ if(current&¤t->failed.load()){+ failed=true;error=current->errorText();armed=false;+ if(firstFrameUs)lastSeconds=double(sink::recordingClockUs()-firstFrameUs)/1e6;+ retire(current,{});current.reset();+ veyra::log::warn("live-recorder",std::format("recording stopped on error: {}",utf8(error)));+ }+ for(auto it=finishing.begin();it!=finishing.end();){+ auto& segment=*it;+ if(!segment->done()){++it;continue;}+ segment->join();+ if(segment->videoWritten.load()){path=segment->path;++saved;}+ if(segment->failed.load()&&error.empty()){failed=true;error=segment->errorText();}+ if(const auto text=segment->noteText();!text.empty())note=text;+ it=finishing.erase(it);+ }+ }+};++LiveRecorder::LiveRecorder():s_(std::make_unique<State>()){}+LiveRecorder::~LiveRecorder(){waitIdle(8000);}- 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={}",- utf8(file), p.width, p.height, p.hevc ? "HEVC" : "H264",- p.hdr ? 1 : 0, p.fps, settings.bitrateMbps, utf8(p.encoderName)));+bool LiveRecorder::start(const RecordingSettings& settings,std::wstring& error){+ error.clear();+ auto& s=*s_;+ std::lock_guard lock(s.m);+ s.reap();+ if(s.armed){error=L"录制已在进行中";return false;}+ if(settings.directory.empty()){error=L"未设置录制保存位置";return false;}+ std::error_code code;+ std::filesystem::create_directories(settings.directory,code);+ if(!std::filesystem::is_directory(settings.directory,code)){error=L"无法创建录制目录:"+settings.directory;return false;}+ ULARGE_INTEGER available{};+ if(GetDiskFreeSpaceExW(settings.directory.c_str(),&available,nullptr,nullptr)&&available.QuadPart<(uint64_t(1)<<30)){+ error=L"录制目录所在磁盘剩余空间不足 1 GB";return false;+ }+ s.settings=settings;s.armed=true;s.failed=false;s.error.clear();s.note.clear();s.encoder.clear();+ s.framesBase=s.droppedBase=0;s.files=0;s.firstFrameUs=0;s.nextDueUs=0;s.lastSeconds=0;s.audioTrack=false;+ s.baseName=L"Veyra-"+fileStamp();s.nextNumber=1;++s.started;+ veyra::log::info("live-recorder",std::format("armed directory={} bitrateMbps={} hevc={} fpsLimit={} audio={}",+ utf8(settings.directory),settings.bitrateMbps,settings.hevc,settings.fpsLimit,settings.audio));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; }+void LiveRecorder::stop(const std::wstring& note){+ auto& s=*s_;+ std::lock_guard lock(s.m);+ s.reap();+ if(!s.armed)return;+ s.armed=false;+ if(s.firstFrameUs)s.lastSeconds=double(sink::recordingClockUs()-s.firstFrameUs)/1e6;+ if(s.current){s.retire(s.current,note);s.current.reset();}+ else if(!note.empty())s.note=note;+ veyra::log::info("live-recorder",std::format("stop requested note={}",utf8(note)));+}++bool LiveRecorder::active() const{std::lock_guard lock(s_->m);return s_->armed;}- // 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;+RecordingStatus LiveRecorder::status() const{+ auto& s=*s_;+ std::lock_guard lock(s.m);+ s.reap();+ RecordingStatus out;+ out.active=s.armed;out.failed=s.failed;out.finishing=!s.finishing.empty();+ out.error=s.error;out.note=s.note;out.files=s.files;out.started=s.started;out.saved=s.saved;+ out.frames=s.framesBase;out.dropped=s.droppedBase;out.path=s.path;out.encoder=s.encoder;out.audio=s.audioTrack;+ if(s.current){+ out.path=s.current->path;out.frames+=s.current->frames.load();out.dropped+=s.current->dropped.load();+ if(const auto name=s.current->encoderText();!name.empty())out.encoder=name;+ out.audio=s.current->audio;+ if(const auto text=s.current->noteText();!text.empty())out.note=text;}- 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)) {+ out.seconds=s.armed?(s.firstFrameUs?double(sink::recordingClockUs()-s.firstFrameUs)/1e6:0.0):s.lastSeconds;+ return out;+}++void LiveRecorder::setPresentRateHint(double fps){if(std::isfinite(fps)&&fps>0)s_->presentFps=fps;}++void LiveRecorder::sessionEnded(const std::wstring& note){stop(note);}++void LiveRecorder::waitIdle(uint32_t timeoutMs){+ stop();+ const auto deadline=std::chrono::steady_clock::now()+std::chrono::milliseconds(timeoutMs);+ for(;;){{- std::lock_guard lock(p.statusMutex);- if (p.error.empty()) p.error = p.encoder->lastError();+ std::lock_guard lock(s_->m);+ s_->reap();+ if(s_->finishing.empty())return;+ if(std::chrono::steady_clock::now()>=deadline){+ // A stuck encoder must not hang the exit: leave its threads running.+ for(auto& segment:s_->finishing){+ veyra::log::error("live-recorder",std::format("segment not finished at exit path={}",utf8(segment->path)));+ if(segment->encoderThread.joinable())segment->encoderThread.detach();+ if(segment->writerThread.joinable())segment->writerThread.detach();+ static std::vector<std::shared_ptr<Segment>> abandoned;abandoned.push_back(segment);+ }+ s_->finishing.clear();+ return;+ }}- veyra::log::error("live-recorder", "encode failed; closing the recording");- end();- return false;+ std::this_thread::sleep_for(std::chrono::milliseconds(20));}- 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();+bool LiveRecorder::record(ID3D12GraphicsCommandList* list,const Frame& frame){+ auto& s=*s_;+ std::lock_guard lock(s.m);+ if(!s.armed||!list||!frame.texture)return false;+ if(s.pendingCapture){s.pendingCapture->discardPending();s.pendingCapture.reset();}+ if(s.current&&s.current->failed.load())s.reap();+ if(!s.armed)return false;+ const int64_t now=sink::recordingClockUs();+ if(s.settings.fpsLimit){+ const int64_t interval=1000000/int64_t(s.settings.fpsLimit);+ if(s.nextDueUs&&now+interval/4<s.nextDueUs)return false;+ s.nextDueUs=(s.nextDueUs&&now-s.nextDueUs<interval)?s.nextDueUs+interval:now+interval;+ }+ if(s.current&&!s.current->matches(frame)){+ veyra::log::info("live-recorder",std::format("picture changed {}x{} hdr={} -> {}x{} hdr={}; continuing in a new file",+ s.current->width,s.current->height,s.current->hdrMode,frame.width,frame.height,frame.hdrMode));+ s.retire(s.current,L"画面尺寸或 HDR 模式变化,已接着写入新文件");s.current.reset();+ }+ if(!s.current){+ auto fail=[&](const std::wstring& reason){+ s.armed=false;s.failed=true;s.error=reason;+ veyra::log::error("live-recorder",std::format("cannot record: {}",utf8(reason)));+ return false;+ };+ auto segment=std::make_shared<Segment>();+ if(FAILED(frame.texture->GetDevice(IID_PPV_ARGS(&segment->device))))return fail(L"无法获取当前显卡");+ segment->vendor=adapterVendor(segment->device.Get());+ segment->nvenc=segment->vendor==0x10DE&&GetEnvironmentVariableW(L"VEYRA_TEST_FORCE_MF_ENCODER",nullptr,0)==0;+ if(frame.hdrMode&&!segment->nvenc)return fail(L"HDR 画面录制需要 NVIDIA 显卡(HEVC 10bit);请关闭 HDR 输出后再录制");+ if(frame.width<16||frame.height<16||(frame.width&1)||(frame.height&1))+ return fail(std::format(L"当前画面尺寸 {}×{} 无法录制",frame.width,frame.height));+ segment->width=frame.width;segment->height=frame.height;segment->hdrMode=frame.hdrMode;+ // H.264 hardware encoders stop at 4096 pixels per side.+ segment->hevc=s.settings.hevc||frame.hdrMode!=0||frame.width>4096||frame.height>4096;+ const double hint=s.presentFps.load();+ segment->fps=s.settings.fpsLimit?s.settings.fpsLimit:uint32_t(std::clamp<long>(std::lround(hint>1?hint:60.0),10,480));+ segment->bitrateMbps=s.settings.bitrateMbps?s.settings.bitrateMbps:autoBitrateMbps(frame.width,frame.height,segment->fps,segment->hevc);+ segment->audio=s.settings.audio;+ std::filesystem::path file;+ for(unsigned attempt=0;;++attempt){+ const auto name=s.baseName+(s.nextNumber>1?std::format(L"-{}",s.nextNumber):L"")+(attempt?std::format(L"-{}",attempt):L"")+L".mp4";+ file=std::filesystem::path(s.settings.directory)/name;+ std::error_code code;+ if(!std::filesystem::exists(file,code))break;}- 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={}",- utf8(p.path), p.frames.load(), p.dropped.load(),- double(p.recordedUs.load()) / 1000000.0, failed ? 1 : 0));+ segment->path=file.wstring();+ std::wstring reason;+ if(!segment->create(reason))return fail(reason);+ s.current=segment;++s.files;++s.nextNumber;s.audioTrack=segment->audio;+ if(segment->audio)sink::setRecordingAudioSink(segment);+ veyra::log::info("live-recorder",std::format("file {} path={} extent={}x{} hdr={} codec={} fps={} bitrateMbps={} encoder={} audio={}",+ s.files,utf8(segment->path),segment->width,segment->height,segment->hdrMode,segment->hevc?"HEVC":"H264",segment->fps,segment->bitrateMbps,+ segment->nvenc?"NVENC":"MediaFoundation",segment->audio));+ }+ if(!s.current->capture(list,frame,now))return false;+ if(!s.firstFrameUs)s.firstFrameUs=now;+ s.pendingCapture=s.current;+ return true;}-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;+void LiveRecorder::submitted(ID3D12Fence* fence,uint64_t value){+ std::lock_guard lock(s_->m);+ if(s_->pendingCapture){s_->pendingCapture->submittedPending(fence,value);s_->pendingCapture.reset();}+}++void LiveRecorder::discarded(){+ std::lock_guard lock(s_->m);+ if(s_->pendingCapture){s_->pendingCapture->discardPending();s_->pendingCapture.reset();}}} // namespace veyra::enginediff --git a/src/engine/VideoPresenter.cpp b/src/engine/VideoPresenter.cppindex f0d5228a..33a1c319 100644--- a/src/engine/VideoPresenter.cpp+++ b/src/engine/VideoPresenter.cpp@@ -328,6 +328,14 @@ bool VideoPresenter::present(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing&barriers[1].Transition.StateBefore=D3D12_RESOURCE_STATE_COPY_SOURCE;barriers[1].Transition.StateAfter=D3D12_RESOURCE_STATE_COMMON;list->ResourceBarrier(1,&barriers[1]);list->ResourceBarrier(1,©);}+ // Live recording reads the frame here, in this list: the source is back in+ // COMMON, and the consumer fence signalled after this list covers the read.+ bool captureRecorded=false;+ struct CaptureGuard{PresentCapture* capture;bool& recorded;~CaptureGuard(){if(recorded&&capture)capture->discarded();}} captureGuard{capture_,captureRecorded};+ if(capture_){+ const uint32_t hdrMode=graph.hdrOutput()?(graph.hdr10Output()?2u:1u):0u;+ captureRecorded=capture_->record(list,{source,graph.outputFormat(),graph.workWidth(),graph.workHeight(),hdrMode,graph.outputDitherStep(),generated});+ }// Interpolation region for the XeSS present-sink FG backend.// It must follow the PresentBlit view mapping (contain * zoom, view// center) rather than assuming the default centered view: the previous@@ -408,6 +416,7 @@ bool VideoPresenter::present(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing&gpuTimer_.mark(list,diagnostics::GpuStage::Blit,true);gpuTimer_.resolve(list);if(!ring.submitAndSignal(commandSlot))return false;gpuTimer_.submitted(ring.lastSignaledValue());+ if(captureRecorded){captureRecorded=false;capture_->submitted(fence,ring.lastSignaledValue());}if(probeIssued){probePending_=true;probeFenceValue_=ring.lastSignaledValue();}// Custom: collect the previous probe as soon as the GPU reports it complete.// GetCompletedValue is a plain read, so presentation never waits here.diff --git a/src/sink/MfVideoEncoder.cpp b/src/sink/MfVideoEncoder.cppindex fb332d46..50b0d82b 100644--- a/src/sink/MfVideoEncoder.cpp+++ b/src/sink/MfVideoEncoder.cpp@@ -1,4 +1,5 @@#include "veyra/sink/VideoEncoder.h"+#include "veyra/sink/MfLiveEncoder.h"#include "veyra/pipeline/EnhanceGraph.h"#include "veyra/pipeline/GpuPassUtils.h"#include "veyra/gfx/D3D12DeviceContext.h"@@ -147,11 +148,18 @@ bool listHardwareMfts(bool hevc,uint32_t adapterVendorId,std::vector<MftCandidatuint32_t alignUp(uint32_t value,uint32_t alignment){return (value+alignment-1)/alignment*alignment;}-class MfVideoEncoder final : public VideoEncoder {+class MfVideoEncoder final : public VideoEncoder, public MfLiveEncoder {public:~MfVideoEncoder() override {close();}bool open(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing& ring,EnhanceGraph& graph,const EncoderConfig& config,PacketWriter writer) override;+ // Live recorder path (MfLiveEncoder.h): packed NV12 in, microseconds in and out.+ bool openLive(uint32_t width,uint32_t height,const EncoderConfig& config,PacketWriter writer) override;+ std::vector<uint8_t> liveHeaders() const override {return extradata_;}+ bool encodeNv12(const uint8_t* y,uint32_t yPitch,const uint8_t* uv,uint32_t uvPitch,int64_t ptsUs) override;+ bool finishLive() override {return finish();}+ std::wstring liveDescription() const override {return describe();}+ std::wstring liveError() const override {return error_;}std::vector<uint8_t> headers() const override {return extradata_;}bool encode(unsigned frameSlot,bool generated,int64_t pts) override;bool finish() override;@@ -172,6 +180,8 @@ private:bool writeSample(IMFSample* sample);bool convertToNv12(unsigned frameSlot,bool generated);bool sampleFromPacked(int64_t pts,IMFSample** sample);+ bool openTransform(const EncoderConfig& config);+ bool submitSample(IMFSample* sample);gfx::D3D12DeviceContext* ctx_=nullptr;gfx::CommandSlotRing* ring_=nullptr;@@ -203,6 +213,9 @@ private:std::vector<uint8_t> packed_;HANDLE fenceEvent_=nullptr;bool mfAcquired_=false;+ // Live recorder: sample times are microseconds (x10 in MF units) and key+ // frames are forced every 2 s of media time instead of every N frames.+ bool liveTimestamps_=false;uint64_t submitted_=0,written_=0;uint64_t nextKeyframe_=0;uint64_t gopLength_=1;@@ -228,6 +241,39 @@ bool MfVideoEncoder::open(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing& rinerror_=std::format(L"Unsupported NV12 extent {}x{}",width_,height_);return false;}+ if(!openTransform(config))return false;+ // Same NV12 conversion the NVENC path uses; the result is read back because+ // MFTs take system-memory NV12 (no shared D3D12 texture contract).+ std::vector<uint8_t> shader;+ error_=L"RgbToNv12 shader load/create failed";+ if(!convert_.loadShader("RgbToNv12.dxil",shader)||!convert_.create(ctx.device(),shader,kOutputPoolSlots+2,1,2))return false;+ for(unsigned i=0;i<kOutputPoolSlots;++i)makeSrv(ctx.device(),i<2?graph.videoFrameResource(i):graph.generatedFrameResource(i-2),graph.outputFormat(),cpuHandleOf(convert_,i));+ error_=L"NV12 conversion/readback allocation failed";+ y_=makeTexture(ctx.device(),width_,height_,DXGI_FORMAT_R8_UNORM,true);+ uv_=makeTexture(ctx.device(),width_/2,height_/2,DXGI_FORMAT_R8G8_UNORM,true);+ if(!y_||!uv_)return false;+ makeUav(ctx.device(),y_.Get(),DXGI_FORMAT_R8_UNORM,cpuHandleOf(convert_,kOutputPoolSlots));+ makeUav(ctx.device(),uv_.Get(),DXGI_FORMAT_R8G8_UNORM,cpuHandleOf(convert_,kOutputPoolSlots+1));+ auto makeReadback=[&](uint32_t rows,uint32_t rowBytes,ComPtr<ID3D12Resource>& out,UINT& pitch){+ pitch=alignUp(rowBytes,256);+ D3D12_HEAP_PROPERTIES hp{};hp.Type=D3D12_HEAP_TYPE_READBACK;+ D3D12_RESOURCE_DESC bd{};bd.Dimension=D3D12_RESOURCE_DIMENSION_BUFFER;bd.Width=uint64_t(pitch)*rows;+ bd.Height=1;bd.DepthOrArraySize=1;bd.MipLevels=1;bd.SampleDesc.Count=1;bd.Layout=D3D12_TEXTURE_LAYOUT_ROW_MAJOR;+ return SUCCEEDED(ctx.device()->CreateCommittedResource(&hp,D3D12_HEAP_FLAG_NONE,&bd,D3D12_RESOURCE_STATE_COPY_DEST,nullptr,IID_PPV_ARGS(&out)));+ };+ if(!makeReadback(height_,width_,yRead_,yPitch_)||!makeReadback(height_/2,width_,uvRead_,uvPitch_))return false;+ packed_.resize(size_t(width_)*height_+size_t(width_)*(height_/2));+ fenceEvent_=CreateEventW(nullptr,FALSE,FALSE,nullptr);+ if(!fenceEvent_){error_=std::format(L"CreateEvent win32={}",GetLastError());return false;}+ if(!check(transform_->ProcessMessage(MFT_MESSAGE_COMMAND_FLUSH,0),L"Flush"))return false;+ if(!check(transform_->ProcessMessage(MFT_MESSAGE_NOTIFY_BEGIN_STREAMING,0),L"BeginStreaming"))return false;+ if(!check(transform_->ProcessMessage(MFT_MESSAGE_NOTIFY_START_OF_STREAM,0),L"StartOfStream"))return false;+ error_.clear();+ return true;+}++// Vendor MFT selection and negotiation, shared by the export and the live recorder.+bool MfVideoEncoder::openTransform(const EncoderConfig& config){if(!acquireMediaFoundation())return false;mfAcquired_=true;std::vector<MftCandidate> candidates;std::wstring detail;@@ -281,33 +327,6 @@ bool MfVideoEncoder::open(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing& rin}if(!check(transform_->GetOutputStreamInfo(outputId_,&outputInfo_),L"GetOutputStreamInfo"))return false;outputProvidesSamples_=(outputInfo_.dwFlags&(MFT_OUTPUT_STREAM_PROVIDES_SAMPLES|MFT_OUTPUT_STREAM_CAN_PROVIDE_SAMPLES))!=0;- // Same NV12 conversion the NVENC path uses; the result is read back because- // MFTs take system-memory NV12 (no shared D3D12 texture contract).- std::vector<uint8_t> shader;- error_=L"RgbToNv12 shader load/create failed";- if(!convert_.loadShader("RgbToNv12.dxil",shader)||!convert_.create(ctx.device(),shader,kOutputPoolSlots+2,1,2))return false;- for(unsigned i=0;i<kOutputPoolSlots;++i)makeSrv(ctx.device(),i<2?graph.videoFrameResource(i):graph.generatedFrameResource(i-2),graph.outputFormat(),cpuHandleOf(convert_,i));- error_=L"NV12 conversion/readback allocation failed";- y_=makeTexture(ctx.device(),width_,height_,DXGI_FORMAT_R8_UNORM,true);- uv_=makeTexture(ctx.device(),width_/2,height_/2,DXGI_FORMAT_R8G8_UNORM,true);- if(!y_||!uv_)return false;- makeUav(ctx.device(),y_.Get(),DXGI_FORMAT_R8_UNORM,cpuHandleOf(convert_,kOutputPoolSlots));- makeUav(ctx.device(),uv_.Get(),DXGI_FORMAT_R8G8_UNORM,cpuHandleOf(convert_,kOutputPoolSlots+1));- auto makeReadback=[&](uint32_t rows,uint32_t rowBytes,ComPtr<ID3D12Resource>& out,UINT& pitch){- pitch=alignUp(rowBytes,256);- D3D12_HEAP_PROPERTIES hp{};hp.Type=D3D12_HEAP_TYPE_READBACK;- D3D12_RESOURCE_DESC bd{};bd.Dimension=D3D12_RESOURCE_DIMENSION_BUFFER;bd.Width=uint64_t(pitch)*rows;- bd.Height=1;bd.DepthOrArraySize=1;bd.MipLevels=1;bd.SampleDesc.Count=1;bd.Layout=D3D12_TEXTURE_LAYOUT_ROW_MAJOR;- return SUCCEEDED(ctx.device()->CreateCommittedResource(&hp,D3D12_HEAP_FLAG_NONE,&bd,D3D12_RESOURCE_STATE_COPY_DEST,nullptr,IID_PPV_ARGS(&out)));- };- if(!makeReadback(height_,width_,yRead_,yPitch_)||!makeReadback(height_/2,width_,uvRead_,uvPitch_))return false;- packed_.resize(size_t(width_)*height_+size_t(width_)*(height_/2));- fenceEvent_=CreateEventW(nullptr,FALSE,FALSE,nullptr);- if(!fenceEvent_){error_=std::format(L"CreateEvent win32={}",GetLastError());return false;}- if(!check(transform_->ProcessMessage(MFT_MESSAGE_COMMAND_FLUSH,0),L"Flush"))return false;- if(!check(transform_->ProcessMessage(MFT_MESSAGE_NOTIFY_BEGIN_STREAMING,0),L"BeginStreaming"))return false;- if(!check(transform_->ProcessMessage(MFT_MESSAGE_NOTIFY_START_OF_STREAM,0),L"StartOfStream"))return false;- error_.clear();return true;}@@ -497,7 +516,8 @@ bool MfVideoEncoder::writeSample(IMFSample* sample){}LONGLONG time=0;if(FAILED(sample->GetSampleTime(&time)))time=0;- const int64_t index=llround(double(time)*double(fpsNum_)/double(fpsDen_)/double(kTicksPerSecond));+ // Export: the ordinal frame index. Live recorder: microseconds.+ const int64_t index=liveTimestamps_?int64_t(time/10):llround(double(time)*double(fpsNum_)/double(fpsDen_)/double(kTicksPerSecond));UINT32 clean=0;const bool key=SUCCEEDED(sample->GetUINT32(MFSampleExtension_CleanPoint,&clean))&&clean!=0;const bool accepted=writer_(data,length,index,key);@@ -646,6 +666,11 @@ bool MfVideoEncoder::encode(unsigned frameSlot,bool generated,int64_t pts){if(!convertToNv12(frameSlot,generated))return false;IMFSample* sample=nullptr;if(!sampleFromPacked(pts,&sample))return false;+ return submitSample(sample);+}++// Takes ownership of `sample`.+bool MfVideoEncoder::submitSample(IMFSample* sample){for(;;){if(async_){if(!waitEvents()){sample->Release();return false;}@@ -669,6 +694,54 @@ bool MfVideoEncoder::encode(unsigned frameSlot,bool generated,int64_t pts){return async_?drainOutputs(false):drainOutputs(true);}+bool MfVideoEncoder::openLive(uint32_t width,uint32_t height,const EncoderConfig& config,PacketWriter writer){+ writer_=std::move(writer);liveTimestamps_=true;+ 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_=width;height_=height;+ error_=L"Media Foundation startup failed; see worker log";+ if(width_<16||height_<16||(width_&1)||(height_&1)){+ log::error("mf-encoder",std::format("unsupported live extent {}x{} for NV12",width_,height_));+ error_=std::format(L"Unsupported NV12 extent {}x{}",width_,height_);+ return false;+ }+ if(!openTransform(config))return false;+ if(!check(transform_->ProcessMessage(MFT_MESSAGE_COMMAND_FLUSH,0),L"Flush"))return false;+ if(!check(transform_->ProcessMessage(MFT_MESSAGE_NOTIFY_BEGIN_STREAMING,0),L"BeginStreaming"))return false;+ if(!check(transform_->ProcessMessage(MFT_MESSAGE_NOTIFY_START_OF_STREAM,0),L"StartOfStream"))return false;+ error_.clear();+ return true;+}++bool MfVideoEncoder::encodeNv12(const uint8_t* y,uint32_t yPitch,const uint8_t* uv,uint32_t uvPitch,int64_t ptsUs){+ if(transform_==nullptr||!liveTimestamps_||!y||!uv)return false;+ // A 2 s GOP of media time whatever the presented rate; the first frame is+ // forced too, which is what makes vendor MFTs emit their first output.+ if(ptsUs>=int64_t(nextKeyframe_)&&codecApi_!=nullptr){+ VARIANT value;VariantInit(&value);value.vt=VT_UI4;value.ulVal=1;+ const HRESULT forced=codecApi_->SetValue(&kPropForceKeyFrame,&value);+ if(FAILED(forced))log::info("mf-encoder",std::format("ForceKeyFrame failed hr={} ptsUs={}",hrName(forced),ptsUs));+ nextKeyframe_=uint64_t(std::max<int64_t>(0,ptsUs))+2000000;+ }+ const DWORD size=DWORD(size_t(width_)*height_*3/2);+ ComPtr<IMFMediaBuffer> buffer;+ if(FAILED(MFCreateMemoryBuffer(size,&buffer))){error_=L"MFCreateMemoryBuffer failed";return false;}+ BYTE* data=nullptr;+ if(FAILED(buffer->Lock(&data,nullptr,nullptr))){error_=L"IMFMediaBuffer::Lock failed";return false;}+ for(uint32_t row=0;row<height_;++row)std::memcpy(data+size_t(row)*width_,y+size_t(row)*yPitch,width_);+ uint8_t* chroma=data+size_t(width_)*height_;+ for(uint32_t row=0;row<height_/2;++row)std::memcpy(chroma+size_t(row)*width_,uv+size_t(row)*uvPitch,width_);+ buffer->Unlock();+ buffer->SetCurrentLength(size);+ ComPtr<IMFSample> created;+ if(FAILED(MFCreateSample(&created))||FAILED(created->AddBuffer(buffer.Get()))){error_=L"MFCreateSample/AddBuffer failed";return false;}+ created->SetSampleTime(LONGLONG(ptsUs)*10);+ created->SetSampleDuration(LONGLONG(kTicksPerSecond)*fpsDen_/fpsNum_);+ if(!sampleSent_)created->SetUINT32(MFSampleExtension_Discontinuity,TRUE);+ return submitSample(created.Detach());+}+bool MfVideoEncoder::finish(){if(transform_==nullptr)return true;if(!draining_){@@ -712,6 +785,7 @@ void MfVideoEncoder::close(){} // namespacestd::unique_ptr<VideoEncoder> createMediaFoundationEncoder(){return std::make_unique<MfVideoEncoder>();}+std::unique_ptr<MfLiveEncoder> createMediaFoundationLiveEncoder(){return std::make_unique<MfVideoEncoder>();}EncoderCapability queryMediaFoundationEncoder(bool hevc){EncoderCapability capability;diff --git a/src/sink/NvencLiveEncoder.cpp b/src/sink/NvencLiveEncoder.cppnew file mode 100644index 00000000..1267284c--- /dev/null+++ b/src/sink/NvencLiveEncoder.cpp@@ -0,0 +1,258 @@+#include "veyra/sink/NvencLiveEncoder.h"+#include "veyra/Log.h"++#include <ffnvcodec/nvEncodeAPI.h>+#include <wrl/client.h>++#include <algorithm>+#include <format>++namespace veyra::sink {+static_assert(NVENCAPI_MAJOR_VERSION==13&&NVENCAPI_MINOR_VERSION==0,"NVENC requires the audited 13.0 ABI headers");+using Microsoft::WRL::ComPtr;++struct NvencLiveEncoder::Impl {+ HMODULE dll=nullptr;+ void* encoder=nullptr;+ NV_ENCODE_API_FUNCTION_LIST api{};+ Config config;+ NV_ENC_BUFFER_FORMAT format=NV_ENC_BUFFER_FORMAT_NV12;+ std::wstring error;+ std::vector<uint8_t> sequence;+ struct Input {+ NV_ENC_REGISTERED_PTR registered=nullptr;+ NV_ENC_INPUT_PTR mapped=nullptr;+ NV_ENC_INPUT_RESOURCE_D3D12 resource{};+ };+ struct Output {+ ComPtr<ID3D12Resource> buffer;+ NV_ENC_REGISTERED_PTR registered=nullptr;+ NV_ENC_INPUT_PTR mapped=nullptr;+ NV_ENC_OUTPUT_RESOURCE_D3D12 resource{};+ uint64_t value=0;+ int64_t ptsUs=0;+ unsigned input=0;+ bool pending=false;+ };+ std::vector<Input> inputs;+ std::vector<Output> outputs;+ uint64_t submitted=0,completed=0,signal=0;+ ComPtr<ID3D12Fence> fence;+ HANDLE event=nullptr;+ unsigned successLogs=0;++ bool fail(std::wstring message){+ error=std::move(message);+ veyra::log::error("nvenc-live",std::string(error.begin(),error.end()));+ return false;+ }+ bool check(NVENCSTATUS code,const char* op){+ if(code==NV_ENC_SUCCESS){+ if(successLogs<16){++successLogs;veyra::log::info("nvenc-live",std::format("{} ok",op));}+ return true;+ }+ const char* detail=encoder&&api.nvEncGetLastErrorString?api.nvEncGetLastErrorString(encoder):"";+ const auto text=std::format("{} status={} {}",op,int(code),detail?detail:"");+ error.assign(text.begin(),text.end());+ veyra::log::error("nvenc-live",text);+ return false;+ }+};++NvencLiveEncoder::NvencLiveEncoder():p_(std::make_unique<Impl>()){}+NvencLiveEncoder::~NvencLiveEncoder(){close();}+std::vector<uint8_t> NvencLiveEncoder::headers() const{return p_->sequence;}+std::wstring NvencLiveEncoder::lastError() const{return p_->error;}+std::wstring NvencLiveEncoder::describe() const{+ return p_->config.hevc?(p_->config.hdr?L"NVIDIA NVENC HEVC 10bit":L"NVIDIA NVENC HEVC"):L"NVIDIA NVENC H.264";+}+size_t NvencLiveEncoder::inFlight() const{return size_t(p_->submitted-p_->completed);}+size_t NvencLiveEncoder::capacity() const{return p_->outputs.size();}++bool NvencLiveEncoder::open(ID3D12Device* device,const Config& config,const std::vector<ID3D12Resource*>& inputTextures){+ auto& p=*p_;+ p.config=config;+ if(!device||inputTextures.empty())return p.fail(L"NVENC: no device or input textures");+ if(config.hdr&&!config.hevc)return p.fail(L"HDR recording requires HEVC Main10");+ if(!config.width||!config.height||(config.width&1)||(config.height&1))+ return p.fail(std::format(L"NVENC: unsupported extent {}x{}",config.width,config.height));+ p.format=config.hdr?NV_ENC_BUFFER_FORMAT_YUV420_10BIT:NV_ENC_BUFFER_FORMAT_NV12;+ 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()));+ using Create=NVENCSTATUS(NVENCAPI*)(NV_ENCODE_API_FUNCTION_LIST*);+ auto create=reinterpret_cast<Create>(GetProcAddress(p.dll,"NvEncodeAPICreateInstance"));+ if(!create)return p.fail(L"NvEncodeAPICreateInstance export missing");+ p.api.version=NV_ENCODE_API_FUNCTION_LIST_VER;+ if(!p.check(create(&p.api),"CreateInstance"))return false;+ NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS session{};+ session.version=NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS_VER;session.apiVersion=NVENCAPI_VERSION;+ session.device=device;session.deviceType=NV_ENC_DEVICE_TYPE_DIRECTX;+ if(!p.check(p.api.nvEncOpenEncodeSessionEx(&session,&p.encoder),"OpenD3D12Session"))return false;+ const GUID codec=config.hevc?NV_ENC_CODEC_HEVC_GUID:NV_ENC_CODEC_H264_GUID;+ int maxWidth=0,maxHeight=0;+ NV_ENC_CAPS_PARAM caps{};caps.version=NV_ENC_CAPS_PARAM_VER;+ caps.capsToQuery=NV_ENC_CAPS_WIDTH_MAX;p.api.nvEncGetEncodeCaps(p.encoder,codec,&caps,&maxWidth);+ caps.capsToQuery=NV_ENC_CAPS_HEIGHT_MAX;p.api.nvEncGetEncodeCaps(p.encoder,codec,&caps,&maxHeight);+ if(maxWidth>0&&maxHeight>0&&(int(config.width)>maxWidth||int(config.height)>maxHeight))+ return p.fail(std::format(L"NVENC {} supports at most {}x{} (requested {}x{})",config.hevc?L"HEVC":L"H.264",maxWidth,maxHeight,config.width,config.height));+ if(config.hdr){+ int tenBit=0;caps.capsToQuery=NV_ENC_CAPS_SUPPORT_10BIT_ENCODE;+ p.api.nvEncGetEncodeCaps(p.encoder,codec,&caps,&tenBit);+ if(!tenBit)return p.fail(L"this GPU's NVENC has no 10-bit HEVC encode");+ }+ // Recording favours quality over latency, but B-frames would reorder the+ // output and make DTS differ from PTS; keep IPPP with a 2 s GOP.+ NV_ENC_PRESET_CONFIG preset{};preset.version=NV_ENC_PRESET_CONFIG_VER;preset.presetCfg.version=NV_ENC_CONFIG_VER;+ if(!p.check(p.api.nvEncGetEncodePresetConfigEx(p.encoder,codec,NV_ENC_PRESET_P4_GUID,NV_ENC_TUNING_INFO_HIGH_QUALITY,&preset),"GetPreset"))return false;+ auto& cfg=preset.presetCfg;+ const uint32_t fps=std::clamp(config.fps,1u,480u);+ cfg.frameIntervalP=1;cfg.gopLength=fps*2;cfg.rcParams.enableLookahead=0;+ const uint32_t bits=std::clamp(config.bitrateMbps,1u,400u)*1000000u;+ cfg.rcParams.rateControlMode=NV_ENC_PARAMS_RC_VBR;+ cfg.rcParams.averageBitRate=bits;+ cfg.rcParams.maxBitRate=bits+bits/2;+ cfg.rcParams.vbvBufferSize=bits/2;+ cfg.rcParams.vbvInitialDelay=cfg.rcParams.vbvBufferSize;+ if(config.hevc){+ auto& hevc=cfg.encodeCodecConfig.hevcConfig;+ hevc.idrPeriod=cfg.gopLength;hevc.repeatSPSPPS=1;+ auto& vui=hevc.hevcVUIParameters;+ vui.videoSignalTypePresentFlag=1;vui.videoFormat=NV_ENC_VUI_VIDEO_FORMAT_UNSPECIFIED;vui.videoFullRangeFlag=0;vui.colourDescriptionPresentFlag=1;+ if(config.hdr){+ cfg.profileGUID=NV_ENC_HEVC_PROFILE_MAIN10_GUID;+ hevc.inputBitDepth=hevc.outputBitDepth=NV_ENC_BIT_DEPTH_10;+ vui.colourPrimaries=NV_ENC_VUI_COLOR_PRIMARIES_BT2020;+ vui.transferCharacteristics=NV_ENC_VUI_TRANSFER_CHARACTERISTIC_SMPTE2084;+ vui.colourMatrix=NV_ENC_VUI_MATRIX_COEFFS_BT2020_NCL;+ }else{+ vui.colourPrimaries=NV_ENC_VUI_COLOR_PRIMARIES_BT709;+ vui.transferCharacteristics=NV_ENC_VUI_TRANSFER_CHARACTERISTIC_BT709;+ vui.colourMatrix=NV_ENC_VUI_MATRIX_COEFFS_BT709;+ }+ }else{+ auto& h264=cfg.encodeCodecConfig.h264Config;+ h264.idrPeriod=cfg.gopLength;h264.repeatSPSPPS=1;+ auto& vui=h264.h264VUIParameters;+ vui.videoSignalTypePresentFlag=1;vui.videoFormat=NV_ENC_VUI_VIDEO_FORMAT_UNSPECIFIED;vui.videoFullRangeFlag=0;vui.colourDescriptionPresentFlag=1;+ vui.colourPrimaries=NV_ENC_VUI_COLOR_PRIMARIES_BT709;+ vui.transferCharacteristics=NV_ENC_VUI_TRANSFER_CHARACTERISTIC_BT709;+ vui.colourMatrix=NV_ENC_VUI_MATRIX_COEFFS_BT709;+ }+ NV_ENC_INITIALIZE_PARAMS init{};init.version=NV_ENC_INITIALIZE_PARAMS_VER;+ init.encodeGUID=codec;init.presetGUID=NV_ENC_PRESET_P4_GUID;init.tuningInfo=NV_ENC_TUNING_INFO_HIGH_QUALITY;+ init.encodeWidth=config.width;init.encodeHeight=config.height;init.darWidth=config.width;init.darHeight=config.height;+ init.frameRateNum=fps;init.frameRateDen=1;init.enablePTD=1;init.encodeConfig=&cfg;+ init.maxEncodeWidth=config.width;init.maxEncodeHeight=config.height;init.bufferFormat=p.format;+ if(!p.check(p.api.nvEncInitializeEncoder(p.encoder,&init),"InitializeEncoder"))return false;+ p.sequence.resize(4096);uint32_t size=0;+ NV_ENC_SEQUENCE_PARAM_PAYLOAD seq{};seq.version=NV_ENC_SEQUENCE_PARAM_PAYLOAD_VER;seq.inBufferSize=4096;seq.spsppsBuffer=p.sequence.data();seq.outSPSPPSPayloadSize=&size;+ if(!p.check(p.api.nvEncGetSequenceParams(p.encoder,&seq),"GetSequenceParams"))return false;+ p.sequence.resize(size);+ const HRESULT fenceResult=device->CreateFence(0,D3D12_FENCE_FLAG_NONE,IID_PPV_ARGS(&p.fence));+ if(FAILED(fenceResult))return p.fail(std::format(L"CreateFence HRESULT=0x{:08X}",unsigned(fenceResult)));+ p.event=CreateEventW(nullptr,FALSE,FALSE,nullptr);+ if(!p.event)return p.fail(std::format(L"CreateEvent win32={}",GetLastError()));+ auto registerResource=[&](ID3D12Resource* resource,bool output,uint32_t width,uint32_t height,NV_ENC_REGISTERED_PTR& registered,NV_ENC_INPUT_PTR& mapped){+ NV_ENC_REGISTER_RESOURCE r{};r.version=NV_ENC_REGISTER_RESOURCE_VER;r.resourceType=NV_ENC_INPUT_RESOURCE_TYPE_DIRECTX;+ r.resourceToRegister=resource;r.width=width;r.height=height;+ r.bufferFormat=output?NV_ENC_BUFFER_FORMAT_U8:p.format;r.bufferUsage=output?NV_ENC_OUTPUT_BITSTREAM:NV_ENC_INPUT_IMAGE;+ if(!p.check(p.api.nvEncRegisterResource(p.encoder,&r),output?"RegisterOutput":"RegisterInput"))return false;+ registered=r.registeredResource;+ NV_ENC_MAP_INPUT_RESOURCE m{};m.version=NV_ENC_MAP_INPUT_RESOURCE_VER;m.registeredResource=registered;+ if(!p.check(p.api.nvEncMapInputResource(p.encoder,&m),"MapResource"))return false;+ mapped=m.mappedResource;return true;+ };+ p.inputs.resize(inputTextures.size());+ for(size_t i=0;i<inputTextures.size();++i){+ auto& in=p.inputs[i];+ if(!registerResource(inputTextures[i],false,config.width,config.height,in.registered,in.mapped))return false;+ in.resource.version=NV_ENC_INPUT_RESOURCE_D3D12_VER;in.resource.pInputBuffer=in.mapped;+ in.resource.inputFencePoint.version=NV_ENC_FENCE_POINT_D3D12_VER;in.resource.inputFencePoint.bWait=1;+ }+ // A frame larger than its raw NV12 size does not occur at these bitrates+ // (the VBV above bounds a frame to half a second of the target).+ const uint64_t bitstreamBytes=std::max<uint64_t>(1u<<20,(uint64_t(config.width)*config.height*3/2+4095)&~4095ull);+ p.outputs.resize(std::min<size_t>(4,inputTextures.size()));+ for(auto& out:p.outputs){+ D3D12_HEAP_PROPERTIES hp{};hp.Type=D3D12_HEAP_TYPE_READBACK;+ D3D12_RESOURCE_DESC bd{};bd.Dimension=D3D12_RESOURCE_DIMENSION_BUFFER;bd.Width=bitstreamBytes;bd.Height=1;bd.DepthOrArraySize=1;+ bd.MipLevels=1;bd.SampleDesc.Count=1;bd.Layout=D3D12_TEXTURE_LAYOUT_ROW_MAJOR;+ const HRESULT hr=device->CreateCommittedResource(&hp,D3D12_HEAP_FLAG_NONE,&bd,D3D12_RESOURCE_STATE_COPY_DEST,nullptr,IID_PPV_ARGS(&out.buffer));+ if(FAILED(hr))return p.fail(std::format(L"bitstream buffer HRESULT=0x{:08X}",unsigned(hr)));+ if(!registerResource(out.buffer.Get(),true,uint32_t(bitstreamBytes),1,out.registered,out.mapped))return false;+ out.resource.version=NV_ENC_OUTPUT_RESOURCE_D3D12_VER;out.resource.pOutputBuffer=out.mapped;+ out.resource.outputFencePoint.version=NV_ENC_FENCE_POINT_D3D12_VER;out.resource.outputFencePoint.pFence=p.fence.Get();+ out.resource.outputFencePoint.bSignal=1;+ }+ veyra::log::info("nvenc-live",std::format("open codec={} hdr={} extent={}x{} fps={} vbrMbps={} inputs={} outputs={} bitstreamBytes={}",+ config.hevc?"HEVC":"H264",config.hdr,config.width,config.height,fps,bits/1000000,p.inputs.size(),p.outputs.size(),bitstreamBytes));+ p.error.clear();+ return true;+}++bool NvencLiveEncoder::submit(unsigned index,ID3D12Fence* waitFence,uint64_t value,int64_t ptsUs,bool forceKey){+ auto& p=*p_;+ if(!p.encoder||index>=p.inputs.size()||!waitFence)return p.fail(L"NVENC submit without a session, input or fence");+ if(p.submitted-p.completed>=p.outputs.size())return p.fail(L"NVENC submit with every output pending");+ auto& in=p.inputs[index];+ auto& out=p.outputs[p.submitted%p.outputs.size()];+ in.resource.inputFencePoint.pFence=waitFence;in.resource.inputFencePoint.waitValue=value;+ out.value=++p.signal;out.resource.outputFencePoint.signalValue=out.value;+ NV_ENC_PIC_PARAMS pic{};pic.version=NV_ENC_PIC_PARAMS_VER;+ pic.inputWidth=p.config.width;pic.inputHeight=p.config.height;+ pic.inputBuffer=&in.resource;pic.outputBitstream=&out.resource;pic.bufferFmt=p.format;+ pic.pictureStruct=NV_ENC_PIC_STRUCT_FRAME;pic.inputTimeStamp=uint64_t(ptsUs);pic.inputDuration=1;+ if(forceKey)pic.encodePicFlags=NV_ENC_PIC_FLAG_FORCEIDR|NV_ENC_PIC_FLAG_OUTPUT_SPSPPS;+ if(!p.check(p.api.nvEncEncodePicture(p.encoder,&pic),"EncodePicture"))return false;+ out.pending=true;out.ptsUs=ptsUs;out.input=index;++p.submitted;+ return true;+}++bool NvencLiveEncoder::takeOldest(Packet& packet,bool wait,uint32_t timeoutMs,bool& ready){+ auto& p=*p_;+ ready=false;+ if(p.completed==p.submitted)return true;+ auto& out=p.outputs[p.completed%p.outputs.size()];+ if(!out.pending)return p.fail(L"NVENC output bookkeeping lost a frame");+ if(p.fence->GetCompletedValue()<out.value){+ if(!wait)return true;+ if(FAILED(p.fence->SetEventOnCompletion(out.value,p.event)))return p.fail(L"NVENC output fence event failed");+ if(WaitForSingleObject(p.event,timeoutMs)!=WAIT_OBJECT_0)+ return p.fail(std::format(L"NVENC output not ready after {} ms",timeoutMs));+ }+ NV_ENC_LOCK_BITSTREAM lock{};lock.version=NV_ENC_LOCK_BITSTREAM_VER;lock.outputBitstream=&out.resource;lock.doNotWait=0;+ if(!p.check(p.api.nvEncLockBitstream(p.encoder,&lock),"LockBitstream"))return false;+ const auto* bytes=static_cast<const uint8_t*>(lock.bitstreamBufferPtr);+ packet.data.assign(bytes,bytes+lock.bitstreamSizeInBytes);+ packet.ptsUs=int64_t(lock.outputTimeStamp);+ packet.key=lock.pictureType==NV_ENC_PIC_TYPE_IDR||lock.pictureType==NV_ENC_PIC_TYPE_I;+ packet.input=out.input;+ if(!p.check(p.api.nvEncUnlockBitstream(p.encoder,&out.resource),"UnlockBitstream"))return false;+ out.pending=false;++p.completed;ready=true;+ return true;+}++void NvencLiveEncoder::close(){+ if(!p_)return;+ auto& p=*p_;+ if(p.encoder){+ // Outputs that never completed are abandoned with the session.+ for(auto& out:p.outputs){+ if(out.mapped)p.api.nvEncUnmapInputResource(p.encoder,out.mapped);+ if(out.registered)p.api.nvEncUnregisterResource(p.encoder,out.registered);+ }+ for(auto& in:p.inputs){+ if(in.mapped)p.api.nvEncUnmapInputResource(p.encoder,in.mapped);+ if(in.registered)p.api.nvEncUnregisterResource(p.encoder,in.registered);+ }+ p.api.nvEncDestroyEncoder(p.encoder);p.encoder=nullptr;+ }+ p.outputs.clear();p.inputs.clear();+ if(p.event){CloseHandle(p.event);p.event=nullptr;}+ p.fence.Reset();+ if(p.dll){FreeLibrary(p.dll);p.dll=nullptr;}+}++} // namespace veyra::sinkdiff --git a/src/sink/RecordingAudioTap.cpp b/src/sink/RecordingAudioTap.cppnew file mode 100644index 00000000..6ce1737f--- /dev/null+++ b/src/sink/RecordingAudioTap.cpp@@ -0,0 +1,31 @@+#include "veyra/sink/RecordingAudioTap.h"++#include <atomic>+#include <chrono>+#include <mutex>++namespace veyra::sink {+namespace {+std::mutex gTapMutex;+std::shared_ptr<RecordingAudioSink> gTap;+std::atomic<bool> gTapActive{false};+}++void setRecordingAudioSink(std::shared_ptr<RecordingAudioSink> sink){+ std::lock_guard lock(gTapMutex);+ gTap=std::move(sink);+ gTapActive.store(gTap!=nullptr,std::memory_order_release);+}++bool recordingAudioActive(){return gTapActive.load(std::memory_order_acquire);}++std::shared_ptr<RecordingAudioSink> recordingAudioSink(){+ std::lock_guard lock(gTapMutex);+ return gTap;+}++int64_t recordingClockUs(){+ return std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::steady_clock::now().time_since_epoch()).count();+}++} // namespace veyra::sinkdiff --git a/src/sink/WasapiAudioSink.cpp b/src/sink/WasapiAudioSink.cppindex 21966823..75726ffa 100644--- a/src/sink/WasapiAudioSink.cpp+++ b/src/sink/WasapiAudioSink.cpp@@ -1,5 +1,6 @@#include "veyra/sink/AudioGain.h"#include "veyra/sink/WasapiAudioSink.h"+#include "veyra/sink/RecordingAudioTap.h"#include "veyra/engine/PlaybackRate.h"#include "veyra/media/NetworkInput.h"#include <functiondiscoverykeys_devpkey.h>@@ -900,6 +901,24 @@ bool AudioRenderer::pumpOnce(AudioPcmSource& pipeline, double* firstWrittenPtsMsconst size_t got = pipeline.pull(chunk_.data(), avail, &firstPts);const auto endPts=pipeline.lastPullEndPtsMs();if (firstWrittenPtsMs) *firstWrittenPtsMs = firstPts;+ // Live recording: the source PCM before gain and mute, stamped with the+ // time its first frame plays. Once the stream runs that comes from the+ // device clock, which the player's A/V sync follows; frames queued in the+ // shared buffer alone read ~40 ms early (engine and device latency).+ // Prefill before Start uses the queue plus the latency measured meanwhile.+ if(got&&!pausedEndpoint_&&recordingAudioActive()){+ if(auto tap=recordingAudioSink()){+ const int64_t queuedUs=recordingClockUs()+int64_t(padding)*1000000/int64_t(sampleRate_);+ int64_t playoutUs=queuedUs+tapLatencyUs_;+ UINT64 pos=0,qpc=0;+ if(started_&&clockFrequency_&&SUCCEEDED(clock_->GetPosition(&pos,&qpc))&&qpc){+ const double played=double(pos-anchorPos_)*sampleRate_/double(clockFrequency_);+ playoutUs=int64_t(qpc/10)+int64_t((double(timelineWriteFrame_.load())-played)*1e6/sampleRate_);+ tapLatencyUs_=std::clamp<int64_t>((tapLatencyUs_*7+(playoutUs-queuedUs))/8,0,250000);+ }+ tap->renderedPcm(chunk_.data(),got,inputFormat_,playoutUs,this);+ }+ }if (!started_ && !got) return checked(render_->ReleaseBuffer(0, 0),"Release empty prefill");// File playback owns a continuous media timeline, so it may explicitly// fill an empty read with silence. Live capture must not invent mediadiff --git a/src/ui/QmlPlayerBridge.cpp b/src/ui/QmlPlayerBridge.cppindex d1617696..a7a46ea1 100644--- a/src/ui/QmlPlayerBridge.cpp+++ b/src/ui/QmlPlayerBridge.cpp@@ -349,6 +349,7 @@ struct QmlPlayerBridge::Impl {QVariantMap prefs;// Live recording state published by the engine (see LiveRecorder.h).QVariantMap recordingState;+ uint64_t recordingSaved = 0; // LiveRecorder's finished-file counter already announced// Custom: the display whose HDR curve is currently applied (see syncHdrDisplayProfile).QString hdrProfileDisplay;// Custom: the title whose curve is currently applied (see syncHdrTitleProfile).@@ -1453,24 +1454,34 @@ 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.+ // Live recording state: the recorder owns the files, this side shows them.{const auto live=impl_->engine.recordingSnapshot();QVariantMap state;state["active"]=live.active;state["failed"]=live.failed;+ state["finishing"]=live.finishing;state["path"]=QString::fromStdWString(live.path);- state["error"]=QString::fromStdWString(live.error);+ state["error"]=live.error.empty()?QString():uiText(live.error);+ state["note"]=live.note.empty()?QString():uiText(live.note);state["encoder"]=QString::fromStdWString(live.encoder);state["frames"]=QVariant::fromValue(qulonglong(live.frames));state["dropped"]=QVariant::fromValue(qulonglong(live.dropped));state["seconds"]=live.seconds;+ state["files"]=int(live.files);+ state["audio"]=live.audio;if(state!=impl_->recordingState){- const bool wasActive=impl_->recordingState.value("active").toBool();+ const auto previous=impl_->recordingState;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);+ // One notice per event: a failure, a finished file, a new file.+ const QString error=state.value("error").toString(),note=state.value("note").toString();+ if(live.failed&&!error.isEmpty()&&error!=previous.value("error").toString())emit notice(error,true);+ if(live.saved!=impl_->recordingSaved){+ impl_->recordingSaved=live.saved;+ emit notice(note.isEmpty()?tr("录制已保存:%1").arg(state.value("path").toString())+ :tr("录制已保存:%1(%2)").arg(state.value("path").toString(),note),false);+ }else if(live.active&&!note.isEmpty()&¬e!=previous.value("note").toString())emit notice(note,false);}}// Custom: a display change re-applies that device's HDR curve. The id check is@@ -6781,9 +6792,9 @@ bool QmlPlayerBridge::setPreference(const QString& key, const QVariant& value) {{"networkPrebuffer", {-1, 60}},// Live recording: the target bitrate for the file, and the frame rate// cap (0 keeps the presented rate).- {"recordBitrateMbps", {1, 400}},+ {"recordBitrateMbps", {0, 400}},{"recordFps", {0, 240}}};- static const QStringList flags{"recordHevc", "subtitleEnabled", "subtitleBackground", "subtitleFit",+ static const QStringList flags{"recordHevc", "recordAudio", "subtitleEnabled", "subtitleBackground", "subtitleFit","subtitleSecondLanguage", "audioForceStereo", "holdCompare","magewellLowLatency", "blackmagicNativeCapture", "captureShowAllFrameRates", "cinePillHidden", "exportStopsPlayback", "obsGameCapture", "autoResume", "fullscreenMemoryProtection", "prewarmEnhancement", "hdrFgCompatibility", "computeOnMonitorGpu", "deinterlace", "networkAutoReconnect"};QVariant stored;@@ -7247,9 +7258,11 @@ QString QmlPlayerBridge::recordingDirectory() const {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); }+// 0 = automatic from the picture size and frame rate (LiveRecorder).+int QmlPlayerBridge::recordingBitrateMbps() const { return std::clamp(impl_->prefInt("recordBitrateMbps", 0), 0, 400); }+int QmlPlayerBridge::recordingFpsLimit() const { return std::clamp(impl_->prefInt("recordFps", 0), 0, 240); }bool QmlPlayerBridge::recordingHevc() const { return impl_->prefBool("recordHevc", false); }+bool QmlPlayerBridge::recordingAudio() const { return impl_->prefBool("recordAudio", true); }bool QmlPlayerBridge::recording() const { return impl_->recordingState.value("active").toBool(); }QVariantMap QmlPlayerBridge::recordingState() const { return impl_->recordingState; }@@ -7261,11 +7274,19 @@ void QmlPlayerBridge::startRecording() {options.bitrateMbps = uint32_t(recordingBitrateMbps());options.hevc = recordingHevc();options.fpsLimit = uint32_t(std::max(0, recordingFpsLimit()));- impl_->engine.requestRecording(options);+ options.audio = recordingAudio();+ std::wstring error;+ if (!impl_->engine.requestRecording(options, error)) { emit notice(uiText(error), true); return; }+ // Shown at once; the poll fills in the file and the counters.+ impl_->recordingState["active"] = true;+ impl_->recordingState["failed"] = false;+ emit recordingChanged();}void QmlPlayerBridge::stopRecording() {if (!recording()) return;impl_->engine.stopRecording();+ impl_->recordingState["active"] = false;+ emit recordingChanged();}void QmlPlayerBridge::toggleRecording() { if (recording()) stopRecording(); else startRecording(); }void QmlPlayerBridge::chooseRecordingDirectory() {