Fix corrupted MP4 recordings on Windows by serializing encoder writes

The WGC capture session uses Direct3D11CaptureFramePool::CreateFreeThreaded,
which dispatches FrameArrived callbacks on thread pool threads concurrently.
MFEncoder::writeFrame() accesses non-thread-safe resources (ID3D11DeviceContext,
IMFSinkWriter, shared staging texture and NV12 buffer) without synchronization,
causing MP4 container corruption when callbacks overlap at high frame rates.

Add a mutex to serialize writeFrame() and finalize() calls, preventing
concurrent access to the D3D context and Media Foundation sink writer.

Fixes #96
This commit is contained in:
Pierre-Adrien Lair
2026-03-24 17:59:27 +01:00
parent 6e69da0379
commit 906c476ebe
2 changed files with 4 additions and 0 deletions
@@ -124,6 +124,7 @@ bool MFEncoder::initialize(const std::wstring& outputPath, int width, int height
}
bool MFEncoder::writeFrame(ID3D11Texture2D* texture, int64_t timestampHns) {
std::lock_guard<std::mutex> lock(writeMutex_);
if (!initialized_ || !sinkWriter_) return false;
context_->CopyResource(stagingTexture_.Get(), texture);
@@ -190,6 +191,7 @@ bool MFEncoder::writeFrame(ID3D11Texture2D* texture, int64_t timestampHns) {
}
bool MFEncoder::finalize() {
std::lock_guard<std::mutex> lock(writeMutex_);
if (!initialized_) return false;
initialized_ = false;
@@ -8,6 +8,7 @@
#include <wrl/client.h>
#include <string>
#include <vector>
#include <mutex>
using Microsoft::WRL::ComPtr;
@@ -32,4 +33,5 @@ private:
int height_ = 0;
int fps_ = 60;
bool initialized_ = false;
std::mutex writeMutex_;
};