BlueGit

ict rusty-teams

Files

rusty-teams / vendor / webrtc-sys / src / nvidia / cuda_context.cpp

cuda_context.cpp

cuda_context.cpp 6.6 KiB Download Raw
1#include "cuda_context.h"
2
3#include "rtc_base/checks.h"
4#include "rtc_base/logging.h"
5
6#if defined(WIN32)
7#include <windows.h>
8#else
9#include <dlfcn.h>
10#endif
11
12#include <iostream>
13#include <mutex>
14
15#if defined(WIN32)
16static const char CUDA_DYNAMIC_LIBRARY[] = "nvcuda.dll";
17#else
18static const char CUDA_DYNAMIC_LIBRARY[] = "libcuda.so.1";
19#endif
20
21namespace livekit_ffi {
22
23#define __CUCTX_CUDA_CALL(call, ret) \
24 CUresult err__ = call; \
25 if (err__ != CUDA_SUCCESS) { \
26 const char* szErrName = NULL; \
27 cuGetErrorName(err__, &szErrName); \
28 RTC_LOG(LS_ERROR) << "CudaContext error " << szErrName; \
29 return ret; \
30 }
31
32#define CUCTX_CUDA_CALL_ERROR(call) \
33 do { \
34 __CUCTX_CUDA_CALL(call, err__); \
35 } while (0)
36
37static void* s_module_ptr = nullptr;
38static const int kRequiredDriverVersion = 11000;
39
40// Serializes access to the singleton context, its reference count, and the
41// dynamically loaded CUDA module.
42static std::mutex& cudaMutex() {
43 static std::mutex mutex;
44 return mutex;
45}
46
47static bool load_cuda_modules() {
48 if (s_module_ptr)
49 return true;
50
51#if defined(WIN32)
52 // dll delay load
53 HMODULE module = LoadLibrary(TEXT("nvcuda.dll"));
54 if (!module) {
55 RTC_LOG(LS_INFO) << "nvcuda.dll is not found.";
56 return false;
57 }
58 s_module_ptr = module;
59#elif defined(__linux__)
60 s_module_ptr = dlopen("libcuda.so.1", RTLD_LAZY | RTLD_GLOBAL);
61 if (!s_module_ptr)
62 return false;
63
64 // Close handle immediately because going to call `dlopen` again
65 // in the implib module when cuda api called on Linux.
66 dlclose(s_module_ptr);
67 s_module_ptr = nullptr;
68#endif
69 return true;
70}
71
72static bool check_cuda_device() {
73 int device_count = 0;
74 int driver_version = 0;
75
76 CUCTX_CUDA_CALL_ERROR(cuDriverGetVersion(&driver_version));
77 if (kRequiredDriverVersion > driver_version) {
78 RTC_LOG(LS_ERROR)
79 << "CUDA driver version is not higher than the required version. "
80 << driver_version;
81 return false;
82 }
83
84 CUresult result = cuInit(0);
85 if (result != CUDA_SUCCESS) {
86 RTC_LOG(LS_ERROR) << "Failed to initialize CUDA.";
87 return false;
88 }
89
90 result = cuDeviceGetCount(&device_count);
91 if (result != CUDA_SUCCESS) {
92 RTC_LOG(LS_ERROR) << "Failed to get CUDA device count.";
93 return false;
94 }
95
96 if (device_count == 0) {
97 RTC_LOG(LS_ERROR) << "No CUDA devices found.";
98 return false;
99 }
100
101 return true;
102}
103
104CudaContext* CudaContext::GetInstance() {
105 static CudaContext instance;
106 return &instance;
107}
108
109bool CudaContext::IsAvailable() {
110 std::lock_guard<std::mutex> lock(cudaMutex());
111 return load_cuda_modules() && check_cuda_device();
112}
113
114bool CudaContext::Initialize() {
115 std::lock_guard<std::mutex> lock(cudaMutex());
116 if (cu_context_ != nullptr) {
117 ++ref_count_;
118 RTC_LOG(LS_INFO) << "CUDA context already initialized; reusing existing "
119 "context (refs="
120 << ref_count_ << ").";
121 return true;
122 }
123
124 bool success = load_cuda_modules();
125 if (!success) {
126 RTC_LOG(LS_ERROR) << "Failed to load CUDA modules. maybe the NVIDIA driver "
127 "is not installed?";
128 return false;
129 }
130
131 int num_devices = 0;
132 CUdevice cu_device = 0;
133 CUcontext context = nullptr;
134
135 int driverVersion = 0;
136
137 CUCTX_CUDA_CALL_ERROR(cuDriverGetVersion(&driverVersion));
138 if (kRequiredDriverVersion > driverVersion) {
139 RTC_LOG(LS_ERROR)
140 << "CUDA driver version is not higher than the required version. "
141 << driverVersion;
142 return false;
143 }
144
145 CUresult result = cuInit(0);
146 if (result != CUDA_SUCCESS) {
147 RTC_LOG(LS_ERROR) << "Failed to initialize CUDA.";
148 return false;
149 }
150
151 result = cuDeviceGetCount(&num_devices);
152 if (result != CUDA_SUCCESS) {
153 RTC_LOG(LS_ERROR) << "Failed to get CUDA device count.";
154 return false;
155 }
156
157 if (num_devices == 0) {
158 RTC_LOG(LS_ERROR) << "No CUDA devices found.";
159 return false;
160 }
161
162 CUCTX_CUDA_CALL_ERROR(cuDeviceGet(&cu_device, 0));
163
164 char device_name[80];
165 CUCTX_CUDA_CALL_ERROR(
166 cuDeviceGetName(device_name, sizeof(device_name), cu_device));
167 RTC_LOG(LS_INFO) << "CUDA device name: " << device_name;
168
169#if CUDA_VERSION >= 13000
170 CUCTX_CUDA_CALL_ERROR(cuCtxCreate(&context, nullptr, 0, cu_device));
171#else
172 CUCTX_CUDA_CALL_ERROR(cuCtxCreate(&context, 0, cu_device));
173#endif
174 if (context == nullptr) {
175 RTC_LOG(LS_ERROR) << "Failed to create CUDA context.";
176 return false;
177 }
178
179 cu_device_ = cu_device;
180 cu_context_ = context;
181 ref_count_ = 1;
182 RTC_LOG(LS_INFO) << "CUDA context initialized (refs=1).";
183
184 return true;
185}
186
187bool CudaContext::IsInitialized() const {
188 std::lock_guard<std::mutex> lock(cudaMutex());
189 return cu_context_ != nullptr;
190}
191
192CUcontext CudaContext::GetContext() const {
193 std::lock_guard<std::mutex> lock(cudaMutex());
194 RTC_DCHECK(cu_context_ != nullptr);
195 // Ensure the context is current
196 CUcontext current;
197 if (cuCtxGetCurrent(&current) != CUDA_SUCCESS) {
198 throw;
199 }
200 if (cu_context_ == current) {
201 return cu_context_;
202 }
203 if (cuCtxSetCurrent(cu_context_) != CUDA_SUCCESS) {
204 throw;
205 }
206 return cu_context_;
207}
208
209void CudaContext::Shutdown() {
210 std::lock_guard<std::mutex> lock(cudaMutex());
211 if (ref_count_ == 0) {
212 return;
213 }
214 --ref_count_;
215 if (ref_count_ > 0) {
216 RTC_LOG(LS_INFO) << "CUDA context released (refs=" << ref_count_ << ").";
217 return;
218 }
219
220 if (cu_context_) {
221 const CUresult result = cuCtxDestroy(cu_context_);
222 // NVIDIA documents that cuCtxDestroy() may report an error from an earlier
223 // asynchronous launch, so the context state is indeterminate after this
224 // call. Never reuse the handle; allow a later Initialize() to create a new
225 // context instead.
226 cu_context_ = nullptr;
227 if (result != CUDA_SUCCESS) {
228 const char* error_name = nullptr;
229 if (cuGetErrorName(result, &error_name) != CUDA_SUCCESS ||
230 error_name == nullptr) {
231 error_name = "unknown";
232 }
233 RTC_LOG(LS_ERROR)
234 << "Failed to destroy CUDA context: " << error_name
235 << " (code=" << static_cast<int>(result)
236 << "); cleanup is indeterminate and CUDA resources may have leaked. "
237 "A later Initialize() will create a new context (refs=0).";
238 } else {
239 RTC_LOG(LS_INFO) << "CUDA context destroyed successfully (refs=0).";
240 }
241 }
242 if (s_module_ptr) {
243#if defined(WIN32)
244 FreeLibrary((HMODULE)s_module_ptr);
245#elif defined(__linux__)
246 dlclose(s_module_ptr);
247#endif
248 s_module_ptr = nullptr;
249 }
250}
251
252} // namespace livekit_ffi