|
| 1 | +// Copyright (c) Meta Platforms, Inc. and affiliates. |
| 2 | +// All rights reserved. |
| 3 | +// |
| 4 | +// This source code is licensed under the BSD-style license found in the |
| 5 | +// LICENSE file in the root directory of this source tree. |
| 6 | + |
| 7 | +#include "GpuEncoder.h" |
| 8 | + |
| 9 | +#include <ATen/cuda/CUDAEvent.h> |
| 10 | +#include <c10/cuda/CUDAStream.h> |
| 11 | +#include <cuda_runtime.h> |
| 12 | +#include <torch/types.h> |
| 13 | + |
| 14 | +#include "CUDACommon.h" |
| 15 | +#include "FFMPEGCommon.h" |
| 16 | + |
| 17 | +extern "C" { |
| 18 | +#include <libavutil/hwcontext_cuda.h> |
| 19 | +#include <libavutil/pixdesc.h> |
| 20 | +} |
| 21 | + |
| 22 | +namespace facebook::torchcodec { |
| 23 | +namespace { |
| 24 | + |
| 25 | +// Redefinition from CudaDeviceInterface.cpp anonymous namespace |
| 26 | +int getFlagsAVHardwareDeviceContextCreate() { |
| 27 | +#if LIBAVUTIL_VERSION_INT >= AV_VERSION_INT(58, 26, 100) |
| 28 | + return AV_CUDA_USE_CURRENT_CONTEXT; |
| 29 | +#else |
| 30 | + return 0; |
| 31 | +#endif |
| 32 | +} |
| 33 | + |
| 34 | +// Redefinition from CudaDeviceInterface.cpp anonymous namespace |
| 35 | +// TODO-VideoEncoder: unify device context creation, add caching to encoder |
| 36 | +UniqueAVBufferRef createHardwareDeviceContext(const torch::Device& device) { |
| 37 | + enum AVHWDeviceType type = av_hwdevice_find_type_by_name("cuda"); |
| 38 | + TORCH_CHECK(type != AV_HWDEVICE_TYPE_NONE, "Failed to find cuda device"); |
| 39 | + |
| 40 | + int deviceIndex = getDeviceIndex(device); |
| 41 | + |
| 42 | + c10::cuda::CUDAGuard deviceGuard(device); |
| 43 | + // We set the device because we may be called from a different thread than |
| 44 | + // the one that initialized the cuda context. |
| 45 | + TORCH_CHECK( |
| 46 | + cudaSetDevice(deviceIndex) == cudaSuccess, "Failed to set CUDA device"); |
| 47 | + |
| 48 | + AVBufferRef* hardwareDeviceCtxRaw = nullptr; |
| 49 | + std::string deviceOrdinal = std::to_string(deviceIndex); |
| 50 | + |
| 51 | + int err = av_hwdevice_ctx_create( |
| 52 | + &hardwareDeviceCtxRaw, |
| 53 | + type, |
| 54 | + deviceOrdinal.c_str(), |
| 55 | + nullptr, |
| 56 | + getFlagsAVHardwareDeviceContextCreate()); |
| 57 | + |
| 58 | + if (err < 0) { |
| 59 | + /* clang-format off */ |
| 60 | + TORCH_CHECK( |
| 61 | + false, |
| 62 | + "Failed to create specified HW device. This typically happens when ", |
| 63 | + "your installed FFmpeg doesn't support CUDA (see ", |
| 64 | + "https://github.com/pytorch/torchcodec#installing-cuda-enabled-torchcodec", |
| 65 | + "). FFmpeg error: ", getFFMPEGErrorStringFromErrorCode(err)); |
| 66 | + /* clang-format on */ |
| 67 | + } |
| 68 | + |
| 69 | + return UniqueAVBufferRef(hardwareDeviceCtxRaw); |
| 70 | +} |
| 71 | + |
| 72 | +} // anonymous namespace |
| 73 | + |
| 74 | +GpuEncoder::GpuEncoder(const torch::Device& device) : device_(device) { |
| 75 | + TORCH_CHECK( |
| 76 | + device_.type() == torch::kCUDA, "Unsupported device: ", device_.str()); |
| 77 | + |
| 78 | + initializeCudaContextWithPytorch(device_); |
| 79 | + initializeHardwareContext(); |
| 80 | +} |
| 81 | + |
| 82 | +GpuEncoder::~GpuEncoder() {} |
| 83 | + |
| 84 | +void GpuEncoder::initializeHardwareContext() { |
| 85 | + hardwareDeviceCtx_ = createHardwareDeviceContext(device_); |
| 86 | + nppCtx_ = getNppStreamContext(device_); |
| 87 | +} |
| 88 | + |
| 89 | +std::optional<const AVCodec*> GpuEncoder::findEncoder( |
| 90 | + const AVCodecID& codecId) { |
| 91 | + void* i = nullptr; |
| 92 | + const AVCodec* codec = nullptr; |
| 93 | + while ((codec = av_codec_iterate(&i)) != nullptr) { |
| 94 | + if (codec->id != codecId || !av_codec_is_encoder(codec)) { |
| 95 | + continue; |
| 96 | + } |
| 97 | + |
| 98 | + const AVCodecHWConfig* config = nullptr; |
| 99 | + for (int j = 0; (config = avcodec_get_hw_config(codec, j)) != nullptr; |
| 100 | + ++j) { |
| 101 | + if (config->device_type == AV_HWDEVICE_TYPE_CUDA) { |
| 102 | + return codec; |
| 103 | + } |
| 104 | + } |
| 105 | + } |
| 106 | + return std::nullopt; |
| 107 | +} |
| 108 | + |
| 109 | +void GpuEncoder::registerHardwareDeviceWithCodec(AVCodecContext* codecContext) { |
| 110 | + TORCH_CHECK( |
| 111 | + hardwareDeviceCtx_, "Hardware device context has not been initialized"); |
| 112 | + TORCH_CHECK(codecContext != nullptr, "codecContext is null"); |
| 113 | + codecContext->hw_device_ctx = av_buffer_ref(hardwareDeviceCtx_.get()); |
| 114 | +} |
| 115 | + |
| 116 | +void GpuEncoder::setupEncodingContext(AVCodecContext* codecContext) { |
| 117 | + TORCH_CHECK( |
| 118 | + hardwareDeviceCtx_, "Hardware device context has not been initialized"); |
| 119 | + TORCH_CHECK(codecContext != nullptr, "codecContext is null"); |
| 120 | + |
| 121 | + codecContext->sw_pix_fmt = AV_PIX_FMT_NV12; |
| 122 | + codecContext->pix_fmt = AV_PIX_FMT_CUDA; |
| 123 | + |
| 124 | + AVBufferRef* hwFramesCtxRef = av_hwframe_ctx_alloc(hardwareDeviceCtx_.get()); |
| 125 | + TORCH_CHECK( |
| 126 | + hwFramesCtxRef != nullptr, |
| 127 | + "Failed to allocate hardware frames context for codec"); |
| 128 | + |
| 129 | + AVHWFramesContext* hwFramesCtx = |
| 130 | + reinterpret_cast<AVHWFramesContext*>(hwFramesCtxRef->data); |
| 131 | + hwFramesCtx->format = codecContext->pix_fmt; |
| 132 | + hwFramesCtx->sw_format = codecContext->sw_pix_fmt; |
| 133 | + hwFramesCtx->width = codecContext->width; |
| 134 | + hwFramesCtx->height = codecContext->height; |
| 135 | + |
| 136 | + int ret = av_hwframe_ctx_init(hwFramesCtxRef); |
| 137 | + if (ret < 0) { |
| 138 | + av_buffer_unref(&hwFramesCtxRef); |
| 139 | + TORCH_CHECK( |
| 140 | + false, |
| 141 | + "Failed to initialize CUDA frames context for codec: ", |
| 142 | + getFFMPEGErrorStringFromErrorCode(ret)); |
| 143 | + } |
| 144 | + |
| 145 | + codecContext->hw_frames_ctx = hwFramesCtxRef; |
| 146 | +} |
| 147 | + |
| 148 | +UniqueAVFrame GpuEncoder::convertTensorToAVFrame( |
| 149 | + const torch::Tensor& tensor, |
| 150 | + [[maybe_unused]] AVPixelFormat targetFormat, |
| 151 | + int frameIndex, |
| 152 | + AVCodecContext* codecContext) { |
| 153 | + TORCH_CHECK(tensor.is_cuda(), "GpuEncoder requires CUDA tensors"); |
| 154 | + TORCH_CHECK( |
| 155 | + tensor.dim() == 3 && tensor.size(0) == 3, |
| 156 | + "Expected 3D RGB tensor (CHW format), got shape: ", |
| 157 | + tensor.sizes()); |
| 158 | + |
| 159 | + return convertRGBTensorToNV12Frame(tensor, frameIndex, codecContext); |
| 160 | +} |
| 161 | + |
| 162 | +UniqueAVFrame GpuEncoder::convertRGBTensorToNV12Frame( |
| 163 | + const torch::Tensor& tensor, |
| 164 | + int frameIndex, |
| 165 | + AVCodecContext* codecContext) { |
| 166 | + UniqueAVFrame avFrame(av_frame_alloc()); |
| 167 | + TORCH_CHECK(avFrame != nullptr, "Failed to allocate AVFrame"); |
| 168 | + |
| 169 | + avFrame->format = AV_PIX_FMT_CUDA; |
| 170 | + avFrame->width = static_cast<int>(tensor.size(2)); |
| 171 | + avFrame->height = static_cast<int>(tensor.size(1)); |
| 172 | + avFrame->pts = frameIndex; |
| 173 | + |
| 174 | + int ret = av_hwframe_get_buffer( |
| 175 | + codecContext ? codecContext->hw_frames_ctx : nullptr, avFrame.get(), 0); |
| 176 | + TORCH_CHECK( |
| 177 | + ret >= 0, |
| 178 | + "Failed to allocate hardware frame: ", |
| 179 | + getFFMPEGErrorStringFromErrorCode(ret)); |
| 180 | + |
| 181 | + at::cuda::CUDAStream currentStream = |
| 182 | + at::cuda::getCurrentCUDAStream(device_.index()); |
| 183 | + |
| 184 | + facebook::torchcodec::convertRGBTensorToNV12Frame( |
| 185 | + tensor, avFrame, device_, nppCtx_, currentStream); |
| 186 | + |
| 187 | + // Set color properties to FFmpeg defaults |
| 188 | + avFrame->colorspace = AVCOL_SPC_SMPTE170M; // BT.601 |
| 189 | + avFrame->color_range = AVCOL_RANGE_MPEG; // Limited range |
| 190 | + |
| 191 | + return avFrame; |
| 192 | +} |
| 193 | + |
| 194 | +} // namespace facebook::torchcodec |
0 commit comments