| 1 | #ifndef WEBRTC_SYS_NVIDIA_CUDA_CONTEXT_H |
| 2 | #define WEBRTC_SYS_NVIDIA_CUDA_CONTEXT_H |
| 3 | |
| 4 | #include <cuda.h> |
| 5 | |
| 6 | namespace livekit_ffi { |
| 7 | |
| 8 | /// @brief Process-wide CUDA context shared by NVIDIA codec factories. |
| 9 | /// |
| 10 | /// Every successful Initialize() call acquires one reference and must be |
| 11 | /// paired with one Shutdown() call. The underlying CUDA context is destroyed |
| 12 | /// when the final reference is released. |
| 13 | class CudaContext { |
| 14 | public: |
| 15 | CudaContext() = default; |
| 16 | ~CudaContext() = default; |
| 17 | |
| 18 | /// @brief Checks whether a compatible CUDA device and driver are available. |
| 19 | /// @return True when CUDA can be used. |
| 20 | static bool IsAvailable(); |
| 21 | |
| 22 | /// @brief Returns the process-wide context manager. |
| 23 | /// @return Non-owning pointer to the singleton context manager. |
| 24 | static CudaContext* GetInstance(); |
| 25 | |
| 26 | /// @brief Acquires a reference to the CUDA context, creating it if needed. |
| 27 | /// @return True on success; false if CUDA initialization fails. |
| 28 | bool Initialize(); |
| 29 | |
| 30 | /// @brief Reports whether the underlying CUDA context exists. |
| 31 | /// @return True after successful initialization and before final shutdown. |
| 32 | bool IsInitialized() const; |
| 33 | |
| 34 | /// @brief Returns the CUDA context and makes it current on the calling |
| 35 | /// thread. |
| 36 | /// @return The initialized CUDA context. |
| 37 | CUcontext GetContext() const; |
| 38 | |
| 39 | /// @brief Releases one reference and destroys the context after the last one. |
| 40 | void Shutdown(); |
| 41 | |
| 42 | private: |
| 43 | CUdevice cu_device_ = 0; |
| 44 | CUcontext cu_context_ = nullptr; |
| 45 | // Guarded by cudaMutex() in cuda_context.cpp. |
| 46 | int ref_count_ = 0; |
| 47 | }; |
| 48 | |
| 49 | } // namespace livekit_ffi |
| 50 | |
| 51 | #endif // WEBRTC_SYS_NVIDIA_CUDA_CONTEXT_H |