hw_context.cpp 945 Bytes
Newer Older
1
#include <libtorio/ffmpeg/hw_context.h>
moto's avatar
moto committed
2

moto-meta's avatar
moto-meta committed
3
namespace torio::io {
moto's avatar
moto committed
4
5
6
7
8
9
10
11
12
13
14
15
16
17
namespace {

static std::mutex MUTEX;
static std::map<int, AVBufferRefPtr> CUDA_CONTEXT_CACHE;

} // namespace

AVBufferRef* get_cuda_context(int index) {
  std::lock_guard<std::mutex> lock(MUTEX);
  if (index == -1) {
    index = 0;
  }
  if (CUDA_CONTEXT_CACHE.count(index) == 0) {
    AVBufferRef* p = nullptr;
18
    int ret = av_hwdevice_ctx_create(
moto's avatar
moto committed
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
        &p, AV_HWDEVICE_TYPE_CUDA, std::to_string(index).c_str(), nullptr, 0);
    TORCH_CHECK(
        ret >= 0,
        "Failed to create CUDA device context on device ",
        index,
        "(",
        av_err2string(ret),
        ")");
    assert(p);
    CUDA_CONTEXT_CACHE.emplace(index, p);
    return p;
  }
  AVBufferRefPtr& buffer = CUDA_CONTEXT_CACHE.at(index);
  return buffer;
}

void clear_cuda_context_cache() {
  std::lock_guard<std::mutex> lock(MUTEX);
  CUDA_CONTEXT_CACHE.clear();
}

moto-meta's avatar
moto-meta committed
40
} // namespace torio::io