Fix NV12 crash issue when recreate camera object

This commit is contained in:
2026-04-02 22:07:27 +11:00
parent 4bedf3a3a2
commit 958cab6ae3
25 changed files with 1459 additions and 393 deletions

View File

@@ -16,6 +16,8 @@
#include <opencv2/imgproc.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/opencv.hpp>
#include <atomic>
#include <condition_variable>
namespace ANSCENTER
{
@@ -37,7 +39,36 @@ namespace ANSCENTER
int64_t _pts;
bool _isPlaying;
std::recursive_mutex _mutex;
// --- Per-client inference guard ---
// Tracks how many GPU frames from this client are currently in-flight
// (grabbed by GetRTSPCVImage but not yet released after inference).
// Destroy() waits for this to reach 0 before freeing NVDEC surfaces,
// preventing the use-after-free crash when LabVIEW stops a camera
// while AI inference is still reading CUDA device pointers.
std::atomic<int> _inFlightFrames{0};
std::condition_variable_any _inFlightDone;
public:
void IncrementInFlight() { _inFlightFrames.fetch_add(1, std::memory_order_acq_rel); }
void DecrementInFlight() {
if (_inFlightFrames.fetch_sub(1, std::memory_order_acq_rel) <= 1) {
_inFlightDone.notify_all();
}
}
// Atomically check _isPlaying AND increment _inFlightFrames under the
// same mutex. Returns true if the caller may proceed to access CUDA
// resources (GetCudaHWFrame + D2D copy). Returns false if the player
// is stopping/reconnecting — caller must NOT touch CUDA resources.
//
// This closes the race window where Reconnect() sets _isPlaying=false
// and calls close() while GetRTSPCVImage is between GetCudaHWFrame()
// and the D2D copy in gpu_frame_attach_cuda().
bool TryIncrementInFlight() {
std::lock_guard<std::recursive_mutex> lock(_mutex);
if (!_isPlaying) return false;
_inFlightFrames.fetch_add(1, std::memory_order_acq_rel);
return true;
}
ANSRTSPClient();
~ANSRTSPClient() noexcept;
[[nodiscard]] bool Init(std::string licenseKey, std::string url);