torchcodec 0.7.0__cp313-cp313-win_amd64.whl → 0.8.0__cp313-cp313-win_amd64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of torchcodec might be problematic. Click here for more details.

Files changed (61) hide show
  1. torchcodec/_core/BetaCudaDeviceInterface.cpp +636 -0
  2. torchcodec/_core/BetaCudaDeviceInterface.h +191 -0
  3. torchcodec/_core/CMakeLists.txt +36 -3
  4. torchcodec/_core/CUDACommon.cpp +315 -0
  5. torchcodec/_core/CUDACommon.h +46 -0
  6. torchcodec/_core/CpuDeviceInterface.cpp +189 -108
  7. torchcodec/_core/CpuDeviceInterface.h +81 -19
  8. torchcodec/_core/CudaDeviceInterface.cpp +211 -368
  9. torchcodec/_core/CudaDeviceInterface.h +33 -6
  10. torchcodec/_core/DeviceInterface.cpp +57 -19
  11. torchcodec/_core/DeviceInterface.h +97 -16
  12. torchcodec/_core/Encoder.cpp +302 -9
  13. torchcodec/_core/Encoder.h +51 -1
  14. torchcodec/_core/FFMPEGCommon.cpp +189 -2
  15. torchcodec/_core/FFMPEGCommon.h +18 -0
  16. torchcodec/_core/FilterGraph.cpp +28 -21
  17. torchcodec/_core/FilterGraph.h +15 -1
  18. torchcodec/_core/Frame.cpp +17 -7
  19. torchcodec/_core/Frame.h +15 -61
  20. torchcodec/_core/Metadata.h +2 -2
  21. torchcodec/_core/NVDECCache.cpp +70 -0
  22. torchcodec/_core/NVDECCache.h +104 -0
  23. torchcodec/_core/SingleStreamDecoder.cpp +202 -198
  24. torchcodec/_core/SingleStreamDecoder.h +39 -14
  25. torchcodec/_core/StreamOptions.h +16 -6
  26. torchcodec/_core/Transform.cpp +60 -0
  27. torchcodec/_core/Transform.h +59 -0
  28. torchcodec/_core/__init__.py +1 -0
  29. torchcodec/_core/custom_ops.cpp +180 -32
  30. torchcodec/_core/fetch_and_expose_non_gpl_ffmpeg_libs.cmake +61 -1
  31. torchcodec/_core/nvcuvid_include/cuviddec.h +1374 -0
  32. torchcodec/_core/nvcuvid_include/nvcuvid.h +610 -0
  33. torchcodec/_core/ops.py +86 -43
  34. torchcodec/_core/pybind_ops.cpp +22 -59
  35. torchcodec/_samplers/video_clip_sampler.py +7 -19
  36. torchcodec/decoders/__init__.py +1 -0
  37. torchcodec/decoders/_decoder_utils.py +61 -1
  38. torchcodec/decoders/_video_decoder.py +56 -20
  39. torchcodec/libtorchcodec_core4.dll +0 -0
  40. torchcodec/libtorchcodec_core5.dll +0 -0
  41. torchcodec/libtorchcodec_core6.dll +0 -0
  42. torchcodec/libtorchcodec_core7.dll +0 -0
  43. torchcodec/libtorchcodec_core8.dll +0 -0
  44. torchcodec/libtorchcodec_custom_ops4.dll +0 -0
  45. torchcodec/libtorchcodec_custom_ops5.dll +0 -0
  46. torchcodec/libtorchcodec_custom_ops6.dll +0 -0
  47. torchcodec/libtorchcodec_custom_ops7.dll +0 -0
  48. torchcodec/libtorchcodec_custom_ops8.dll +0 -0
  49. torchcodec/libtorchcodec_pybind_ops4.pyd +0 -0
  50. torchcodec/libtorchcodec_pybind_ops5.pyd +0 -0
  51. torchcodec/libtorchcodec_pybind_ops6.pyd +0 -0
  52. torchcodec/libtorchcodec_pybind_ops7.pyd +0 -0
  53. torchcodec/libtorchcodec_pybind_ops8.pyd +0 -0
  54. torchcodec/samplers/_time_based.py +8 -0
  55. torchcodec/version.py +1 -1
  56. {torchcodec-0.7.0.dist-info → torchcodec-0.8.0.dist-info}/METADATA +24 -13
  57. torchcodec-0.8.0.dist-info/RECORD +80 -0
  58. {torchcodec-0.7.0.dist-info → torchcodec-0.8.0.dist-info}/WHEEL +1 -1
  59. torchcodec-0.7.0.dist-info/RECORD +0 -67
  60. {torchcodec-0.7.0.dist-info → torchcodec-0.8.0.dist-info}/licenses/LICENSE +0 -0
  61. {torchcodec-0.7.0.dist-info → torchcodec-0.8.0.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,191 @@
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
+ // BETA CUDA device interface that provides direct control over NVDEC
8
+ // while keeping FFmpeg for demuxing. A lot of the logic, particularly the use
9
+ // of a cache for the decoders, is inspired by DALI's implementation which is
10
+ // APACHE 2.0:
11
+ // https://github.com/NVIDIA/DALI/blob/c7539676a24a8e9e99a6e8665e277363c5445259/dali/operators/video/frames_decoder_gpu.cc#L1
12
+ //
13
+ // NVDEC / NVCUVID docs:
14
+ // https://docs.nvidia.com/video-technologies/video-codec-sdk/13.0/nvdec-video-decoder-api-prog-guide/index.html#using-nvidia-video-decoder-nvdecode-api
15
+
16
+ #pragma once
17
+
18
+ #include "src/torchcodec/_core/CUDACommon.h"
19
+ #include "src/torchcodec/_core/Cache.h"
20
+ #include "src/torchcodec/_core/DeviceInterface.h"
21
+ #include "src/torchcodec/_core/FFMPEGCommon.h"
22
+ #include "src/torchcodec/_core/NVDECCache.h"
23
+
24
+ #include <map>
25
+ #include <memory>
26
+ #include <mutex>
27
+ #include <queue>
28
+ #include <unordered_map>
29
+ #include <vector>
30
+
31
+ #include "src/torchcodec/_core/nvcuvid_include/cuviddec.h"
32
+ #include "src/torchcodec/_core/nvcuvid_include/nvcuvid.h"
33
+
34
+ namespace facebook::torchcodec {
35
+
36
+ class BetaCudaDeviceInterface : public DeviceInterface {
37
+ public:
38
+ explicit BetaCudaDeviceInterface(const torch::Device& device);
39
+ virtual ~BetaCudaDeviceInterface();
40
+
41
+ void initialize(
42
+ const AVStream* avStream,
43
+ const UniqueDecodingAVFormatContext& avFormatCtx) override;
44
+
45
+ void convertAVFrameToFrameOutput(
46
+ UniqueAVFrame& avFrame,
47
+ FrameOutput& frameOutput,
48
+ std::optional<torch::Tensor> preAllocatedOutputTensor =
49
+ std::nullopt) override;
50
+
51
+ bool canDecodePacketDirectly() const override {
52
+ return true;
53
+ }
54
+
55
+ int sendPacket(ReferenceAVPacket& packet) override;
56
+ int sendEOFPacket() override;
57
+ int receiveFrame(UniqueAVFrame& avFrame) override;
58
+ void flush() override;
59
+
60
+ // NVDEC callback functions (must be public for C callbacks)
61
+ int streamPropertyChange(CUVIDEOFORMAT* videoFormat);
62
+ int frameReadyForDecoding(CUVIDPICPARAMS* picParams);
63
+ int frameReadyInDisplayOrder(CUVIDPARSERDISPINFO* dispInfo);
64
+
65
+ private:
66
+ int sendCuvidPacket(CUVIDSOURCEDATAPACKET& cuvidPacket);
67
+
68
+ void initializeBSF(
69
+ const AVCodecParameters* codecPar,
70
+ const UniqueDecodingAVFormatContext& avFormatCtx);
71
+ // Apply bitstream filter, returns filtered packet or original if no filter
72
+ // needed.
73
+ ReferenceAVPacket& applyBSF(
74
+ ReferenceAVPacket& packet,
75
+ ReferenceAVPacket& filteredPacket);
76
+
77
+ CUdeviceptr previouslyMappedFrame_ = 0;
78
+ void unmapPreviousFrame();
79
+
80
+ UniqueAVFrame convertCudaFrameToAVFrame(
81
+ CUdeviceptr framePtr,
82
+ unsigned int pitch,
83
+ const CUVIDPARSERDISPINFO& dispInfo);
84
+
85
+ CUvideoparser videoParser_ = nullptr;
86
+ UniqueCUvideodecoder decoder_;
87
+ CUVIDEOFORMAT videoFormat_ = {};
88
+
89
+ std::queue<CUVIDPARSERDISPINFO> readyFrames_;
90
+
91
+ bool eofSent_ = false;
92
+
93
+ AVRational timeBase_ = {0, 1};
94
+ AVRational frameRateAvgFromFFmpeg_ = {0, 1};
95
+
96
+ UniqueAVBSFContext bitstreamFilter_;
97
+
98
+ // NPP context for color conversion
99
+ UniqueNppContext nppCtx_;
100
+ };
101
+
102
+ } // namespace facebook::torchcodec
103
+
104
+ /* clang-format off */
105
+ // Note: [General design, sendPacket, receiveFrame, frame ordering and NVCUVID callbacks]
106
+ //
107
+ // At a high level, this decoding interface mimics the FFmpeg send/receive
108
+ // architecture:
109
+ // - sendPacket(AVPacket) sends an AVPacket from the FFmpeg demuxer to the
110
+ // NVCUVID parser.
111
+ // - receiveFrame(AVFrame) is a non-blocking call:
112
+ // - if a frame is ready **in display order**, it must return it. By display
113
+ // order, we mean that receiveFrame() must return frames with increasing pts
114
+ // values when called successively.
115
+ // - if no frame is ready, it must return AVERROR(EAGAIN) to indicate the
116
+ // caller should send more packets.
117
+ //
118
+ // The rest of this note assumes you have a reasonable level of familiarity with
119
+ // the sendPacket/receiveFrame calling pattern. If you don't, look up the core
120
+ // decoding loop in SingleVideoDecoder.
121
+ //
122
+ // The frame re-ordering problem:
123
+ // Depending on the codec and on the encoding parameters, a packet from a video
124
+ // stream may contain exactly one frame, more than one frame, or a fraction of a
125
+ // frame. And, there may be non-linear frame dependencies because of B-frames,
126
+ // which need both past *and* future frames to be decoded. Consider the
127
+ // following stream, with frames presented in display order: I0 B1 P2 B3 P4 ...
128
+ // - I0 is an I-frame (also key frame, can be decoded independently)
129
+ // - B1 is a B-frame (bi-directional) which needs both I0 and P2 to be decoded
130
+ // - P2 is a P-frame (predicted frame) which only needs I0 to be decodec.
131
+ //
132
+ // Because B1 needs both I0 and P2 to be properly decoded, the decode order
133
+ // (packet order), defined by the encoder, must be: I0 P2 B1 P4 B3 ... which is
134
+ // different from the display order.
135
+ //
136
+ // SendPacket(AVPacket)'s job is just to pass down the packet to the NVCUVID
137
+ // parser by calling cuvidParseVideoData(packet). When
138
+ // cuvidParseVideoData(packet) is called, it may trigger callbacks,
139
+ // particularly:
140
+ // - streamPropertyChange(videoFormat): triggered once at the start of the
141
+ // stream, and possibly later if the stream properties change (e.g.
142
+ // resolution).
143
+ // - frameReadyForDecoding(picParams)): triggered **in decode order** when the
144
+ // parser has accumulated enough data to decode a frame. We send that frame to
145
+ // the NVDEC hardware for **async** decoding.
146
+ // - frameReadyInDisplayOrder(dispInfo)): triggered **in display order** when a
147
+ // frame is ready to be "displayed" (returned). At that point, the parser also
148
+ // gives us the pts of that frame. We store (a reference to) that frame in a
149
+ // FIFO queue: readyFrames_.
150
+ //
151
+ // When receiveFrame(AVFrame) is called, if readyFrames_ is not empty, we pop
152
+ // the front of the queue, which is the next frame in display order, and map it
153
+ // to an AVFrame by calling cuvidMapVideoFrame(). If readyFrames_ is empty we
154
+ // return EAGAIN to indicate the caller should send more packets.
155
+ //
156
+ // There is potentially a small inefficiency due to the callback design: in
157
+ // order for us to know that a frame is ready in display order, we need the
158
+ // frameReadyInDisplayOrder callback to be triggered. This can only happen
159
+ // within cuvidParseVideoData(packet) in sendPacket(). This means there may be
160
+ // the following sequence of calls:
161
+ //
162
+ // sendPacket(relevantAVPacket)
163
+ // cuvidParseVideoData(relevantAVPacket)
164
+ // frameReadyForDecoding()
165
+ // cuvidDecodePicture() Send frame to NVDEC for async decoding
166
+ //
167
+ // receiveFrame() -> EAGAIN Frame is potentially already decoded
168
+ // and could be returned, but we don't
169
+ // know because frameReadyInDisplayOrder
170
+ // hasn't been triggered yet. We'll only
171
+ // know after sending another,
172
+ // potentially irrelevant packet.
173
+ //
174
+ // sendPacket(irrelevantAVPacket)
175
+ // cuvidParseVideoData(irrelevantAVPacket)
176
+ // frameReadyInDisplayOrder() Only now do we know that our target
177
+ // frame is ready.
178
+ //
179
+ // receiveFrame() return target frame
180
+ //
181
+ // How much this matters in practice is unclear, but probably negligible in
182
+ // general. Particularly when frames are decoded consecutively anyway, the
183
+ // "irrelevantPacket" is actually relevant for a future target frame.
184
+ //
185
+ // Note that the alternative is to *not* rely on the frameReadyInDisplayOrder
186
+ // callback. It's technically possible, but it would mean we now have to solve
187
+ // two hard, *codec-dependent* problems that the callback was solving for us:
188
+ // - we have to guess the frame's pts ourselves
189
+ // - we have to re-order the frames ourselves to preserve display order.
190
+ //
191
+ /* clang-format on */
@@ -95,10 +95,11 @@ function(make_torchcodec_libraries
95
95
  SingleStreamDecoder.cpp
96
96
  Encoder.cpp
97
97
  ValidationUtils.cpp
98
+ Transform.cpp
98
99
  )
99
100
 
100
101
  if(ENABLE_CUDA)
101
- list(APPEND core_sources CudaDeviceInterface.cpp)
102
+ list(APPEND core_sources CudaDeviceInterface.cpp BetaCudaDeviceInterface.cpp NVDECCache.cpp CUDACommon.cpp)
102
103
  endif()
103
104
 
104
105
  set(core_library_dependencies
@@ -107,9 +108,27 @@ function(make_torchcodec_libraries
107
108
  )
108
109
 
109
110
  if(ENABLE_CUDA)
111
+ # Try to find NVCUVID. Try the normal way first. This should work locally.
112
+ find_library(NVCUVID_LIBRARY NAMES nvcuvid)
113
+ # If not found, try with version suffix, or hardcoded path. Appears
114
+ # to be necessary on the CI.
115
+ if(NOT NVCUVID_LIBRARY)
116
+ find_library(NVCUVID_LIBRARY NAMES nvcuvid.1 PATHS /usr/lib64 /usr/lib)
117
+ endif()
118
+ if(NOT NVCUVID_LIBRARY)
119
+ set(NVCUVID_LIBRARY "/usr/lib64/libnvcuvid.so.1")
120
+ endif()
121
+
122
+ if(NVCUVID_LIBRARY)
123
+ message(STATUS "Found NVCUVID: ${NVCUVID_LIBRARY}")
124
+ else()
125
+ message(FATAL_ERROR "Could not find NVCUVID library")
126
+ endif()
127
+
110
128
  list(APPEND core_library_dependencies
111
129
  ${CUDA_nppi_LIBRARY}
112
130
  ${CUDA_nppicc_LIBRARY}
131
+ ${NVCUVID_LIBRARY}
113
132
  )
114
133
  endif()
115
134
 
@@ -175,12 +194,23 @@ function(make_torchcodec_libraries
175
194
  # stray initialization of py::objects. The rest of the object code must
176
195
  # match. See:
177
196
  # https://pybind11.readthedocs.io/en/stable/faq.html#someclass-declared-with-greater-visibility-than-the-type-of-its-field-someclass-member-wattributes
178
- if(NOT WIN32)
197
+ # We have to do this for both pybind_ops and custom_ops because they include
198
+ # some of the same headers.
199
+ #
200
+ # Note that this is Linux only. It's not necessary on Windows, and on Mac
201
+ # hiding visibility can actually break dyanmic casts across share libraries
202
+ # because the type infos don't get exported.
203
+ if(LINUX)
179
204
  target_compile_options(
180
205
  ${pybind_ops_library_name}
181
206
  PUBLIC
182
207
  "-fvisibility=hidden"
183
208
  )
209
+ target_compile_options(
210
+ ${custom_ops_library_name}
211
+ PUBLIC
212
+ "-fvisibility=hidden"
213
+ )
184
214
  endif()
185
215
 
186
216
  # The value we use here must match the value we return from
@@ -233,11 +263,12 @@ if(DEFINED ENV{BUILD_AGAINST_ALL_FFMPEG_FROM_S3})
233
263
  you still need a different FFmpeg to be installed for run time!"
234
264
  )
235
265
 
236
- # This will expose the ffmpeg4, ffmpeg5, ffmpeg6, and ffmpeg7 targets
266
+ # This will expose the ffmpeg4, ffmpeg5, ffmpeg6, ffmpeg7, and ffmpeg8 targets
237
267
  include(
238
268
  ${CMAKE_CURRENT_SOURCE_DIR}/fetch_and_expose_non_gpl_ffmpeg_libs.cmake
239
269
  )
240
270
 
271
+ make_torchcodec_libraries(8 ffmpeg8)
241
272
  make_torchcodec_libraries(7 ffmpeg7)
242
273
  make_torchcodec_libraries(6 ffmpeg6)
243
274
  make_torchcodec_libraries(4 ffmpeg4)
@@ -274,6 +305,8 @@ else()
274
305
  set(ffmpeg_major_version "6")
275
306
  elseif (${libavcodec_major_version} STREQUAL "61")
276
307
  set(ffmpeg_major_version "7")
308
+ elseif (${libavcodec_major_version} STREQUAL "62")
309
+ set(ffmpeg_major_version "8")
277
310
  else()
278
311
  message(
279
312
  FATAL_ERROR
@@ -0,0 +1,315 @@
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 "src/torchcodec/_core/CUDACommon.h"
8
+
9
+ namespace facebook::torchcodec {
10
+
11
+ namespace {
12
+
13
+ // Pytorch can only handle up to 128 GPUs.
14
+ // https://github.com/pytorch/pytorch/blob/e30c55ee527b40d67555464b9e402b4b7ce03737/c10/cuda/CUDAMacros.h#L44
15
+ const int MAX_CUDA_GPUS = 128;
16
+ // Set to -1 to have an infinitely sized cache. Set it to 0 to disable caching.
17
+ // Set to a positive number to have a cache of that size.
18
+ const int MAX_CONTEXTS_PER_GPU_IN_CACHE = -1;
19
+
20
+ PerGpuCache<NppStreamContext> g_cached_npp_ctxs(
21
+ MAX_CUDA_GPUS,
22
+ MAX_CONTEXTS_PER_GPU_IN_CACHE);
23
+
24
+ } // namespace
25
+
26
+ void initializeCudaContextWithPytorch(const torch::Device& device) {
27
+ // It is important for pytorch itself to create the cuda context. If ffmpeg
28
+ // creates the context it may not be compatible with pytorch.
29
+ // This is a dummy tensor to initialize the cuda context.
30
+ torch::Tensor dummyTensorForCudaInitialization = torch::zeros(
31
+ {1}, torch::TensorOptions().dtype(torch::kUInt8).device(device));
32
+ }
33
+
34
+ /* clang-format off */
35
+ // Note: [YUV -> RGB Color Conversion, color space and color range]
36
+ //
37
+ // The frames we get from the decoder (FFmpeg decoder, or NVCUVID) are in YUV
38
+ // format. We need to convert them to RGB. This note attempts to describe this
39
+ // process. There may be some inaccuracies and approximations that experts will
40
+ // notice, but our goal is only to provide a good enough understanding of the
41
+ // process for torchcodec developers to implement and maintain it.
42
+ // On CPU, filtergraph and swscale handle everything for us. With CUDA, we have
43
+ // to do a lot of the heavy lifting ourselves.
44
+ //
45
+ // Color space and color range
46
+ // ---------------------------
47
+ // Two main characteristics of a frame will affect the conversion process:
48
+ // 1. Color space: This basically defines what YUV values correspond to which
49
+ // physical wavelength. No need to go into details here,the point is that
50
+ // videos can come in different color spaces, the most common ones being
51
+ // BT.601 and BT.709, but there are others.
52
+ // In FFmpeg this is represented with AVColorSpace:
53
+ // https://ffmpeg.org/doxygen/4.0/pixfmt_8h.html#aff71a069509a1ad3ff54d53a1c894c85
54
+ // 2. Color range: This defines the range of YUV values. There is:
55
+ // - full range, also called PC range: AVCOL_RANGE_JPEG
56
+ // - and the "limited" range, also called studio or TV range: AVCOL_RANGE_MPEG
57
+ // https://ffmpeg.org/doxygen/4.0/pixfmt_8h.html#a3da0bf691418bc22c4bcbe6583ad589a
58
+ //
59
+ // Color space and color range are independent concepts, so we can have a BT.709
60
+ // with full range, and another one with limited range. Same for BT.601.
61
+ //
62
+ // In the first version of this note we'll focus on the full color range. It
63
+ // will later be updated to account for the limited range.
64
+ //
65
+ // Color conversion matrix
66
+ // -----------------------
67
+ // YUV -> RGB conversion is defined as the reverse process of the RGB -> YUV,
68
+ // So this is where we'll start.
69
+ // At the core of a RGB -> YUV conversion are the "luma coefficients", which are
70
+ // specific to a given color space and defined by the color space standard. In
71
+ // FFmpeg they can be found here:
72
+ // https://github.com/FFmpeg/FFmpeg/blob/7d606ef0ccf2946a4a21ab1ec23486cadc21864b/libavutil/csp.c#L46-L56
73
+ //
74
+ // For example, the BT.709 coefficients are: kr=0.2126, kg=0.7152, kb=0.0722
75
+ // Coefficients must sum to 1.
76
+ //
77
+ // Conventionally Y is in [0, 1] range, and U and V are in [-0.5, 0.5] range
78
+ // (that's mathematically, in practice they are represented in integer range).
79
+ // The conversion is defined as:
80
+ // https://en.wikipedia.org/wiki/YCbCr#R'G'B'_to_Y%E2%80%B2PbPr
81
+ // Y = kr*R + kg*G + kb*B
82
+ // U = (B - Y) * 0.5 / (1 - kb) = (B - Y) / u_scale where u_scale = 2 * (1 - kb)
83
+ // V = (R - Y) * 0.5 / (1 - kr) = (R - Y) / v_scale where v_scale = 2 * (1 - kr)
84
+ //
85
+ // Putting all this into matrix form, we get:
86
+ // [Y] = [kr kg kb ] [R]
87
+ // [U] [-kr/u_scale -kg/u_scale (1-kb)/u_scale] [G]
88
+ // [V] [(1-kr)/v_scale -kg/v_scale -kb)/v_scale ] [B]
89
+ //
90
+ //
91
+ // Now, to convert YUV to RGB, we just need to invert this matrix:
92
+ // ```py
93
+ // import torch
94
+ // kr, kg, kb = 0.2126, 0.7152, 0.0722 # BT.709 luma coefficients
95
+ // u_scale = 2 * (1 - kb)
96
+ // v_scale = 2 * (1 - kr)
97
+ //
98
+ // rgb_to_yuv = torch.tensor([
99
+ // [kr, kg, kb],
100
+ // [-kr/u_scale, -kg/u_scale, (1-kb)/u_scale],
101
+ // [(1-kr)/v_scale, -kg/v_scale, -kb/v_scale]
102
+ // ])
103
+ //
104
+ // yuv_to_rgb_full = torch.linalg.inv(rgb_to_yuv)
105
+ // print("YUV->RGB matrix (Full Range):")
106
+ // print(yuv_to_rgb_full)
107
+ // ```
108
+ // And we get:
109
+ // tensor([[ 1.0000e+00, -3.3142e-09, 1.5748e+00],
110
+ // [ 1.0000e+00, -1.8732e-01, -4.6812e-01],
111
+ // [ 1.0000e+00, 1.8556e+00, 4.6231e-09]])
112
+ //
113
+ // Which matches https://en.wikipedia.org/wiki/YCbCr#ITU-R_BT.709_conversion
114
+ //
115
+ // Color conversion in NPP
116
+ // -----------------------
117
+ // https://docs.nvidia.com/cuda/npp/image_color_conversion.html.
118
+ //
119
+ // NPP provides different ways to convert YUV to RGB:
120
+ // - pre-defined color conversion functions like
121
+ // nppiNV12ToRGB_709CSC_8u_P2C3R_Ctx and nppiNV12ToRGB_709HDTV_8u_P2C3R_Ctx
122
+ // which are for BT.709 limited and full range, respectively.
123
+ // - generic color conversion functions that accept a custom color conversion
124
+ // matrix, called ColorTwist, like nppiNV12ToRGB_8u_ColorTwist32f_P2C3R_Ctx
125
+ //
126
+ // We use the pre-defined functions or the color twist functions depending on
127
+ // which one we find to be closer to the CPU results.
128
+ //
129
+ // The color twist functionality is *partially* described in a section named
130
+ // "YUVToRGBColorTwist". Importantly:
131
+ //
132
+ // - The `nppiNV12ToRGB_8u_ColorTwist32f_P2C3R_Ctx` function takes the YUV data
133
+ // and the color-conversion matrix as input. The function itself and the
134
+ // matrix assume different ranges for YUV values:
135
+ // - The **matrix coefficient** must assume that Y is in [0, 1] and U,V are in
136
+ // [-0.5, 0.5]. That's how we defined our matrix above.
137
+ // - The function `nppiNV12ToRGB_8u_ColorTwist32f_P2C3R_Ctx` however expects all
138
+ // of the input Y, U, V to be in [0, 255]. That's how the data comes out of
139
+ // the decoder.
140
+ // - But *internally*, `nppiNV12ToRGB_8u_ColorTwist32f_P2C3R_Ctx` needs U and V to
141
+ // be centered around 0, i.e. in [-128, 127]. So we need to apply a -128
142
+ // offset to U and V. Y doesn't need to be offset. The offset can be applied
143
+ // by adding a 4th column to the matrix.
144
+ //
145
+ //
146
+ // So our conversion matrix becomes the following, with new offset column:
147
+ // tensor([[ 1.0000e+00, -3.3142e-09, 1.5748e+00, 0]
148
+ // [ 1.0000e+00, -1.8732e-01, -4.6812e-01, -128]
149
+ // [ 1.0000e+00, 1.8556e+00, 4.6231e-09 , -128]])
150
+ //
151
+ // And that's what we need to pass for BT701, full range.
152
+ /* clang-format on */
153
+
154
+ // BT.709 full range color conversion matrix for YUV to RGB conversion.
155
+ // See Note [YUV -> RGB Color Conversion, color space and color range]
156
+ const Npp32f bt709FullRangeColorTwist[3][4] = {
157
+ {1.0f, 0.0f, 1.5748f, 0.0f},
158
+ {1.0f, -0.187324273f, -0.468124273f, -128.0f},
159
+ {1.0f, 1.8556f, 0.0f, -128.0f}};
160
+
161
+ torch::Tensor convertNV12FrameToRGB(
162
+ UniqueAVFrame& avFrame,
163
+ const torch::Device& device,
164
+ const UniqueNppContext& nppCtx,
165
+ at::cuda::CUDAStream nvdecStream,
166
+ std::optional<torch::Tensor> preAllocatedOutputTensor) {
167
+ auto frameDims = FrameDims(avFrame->height, avFrame->width);
168
+ torch::Tensor dst;
169
+ if (preAllocatedOutputTensor.has_value()) {
170
+ dst = preAllocatedOutputTensor.value();
171
+ } else {
172
+ dst = allocateEmptyHWCTensor(frameDims, device);
173
+ }
174
+
175
+ // We need to make sure NVDEC has finished decoding a frame before
176
+ // color-converting it with NPP.
177
+ // So we make the NPP stream wait for NVDEC to finish.
178
+ at::cuda::CUDAStream nppStream =
179
+ at::cuda::getCurrentCUDAStream(device.index());
180
+ at::cuda::CUDAEvent nvdecDoneEvent;
181
+ nvdecDoneEvent.record(nvdecStream);
182
+ nvdecDoneEvent.block(nppStream);
183
+
184
+ nppCtx->hStream = nppStream.stream();
185
+ cudaError_t err = cudaStreamGetFlags(nppCtx->hStream, &nppCtx->nStreamFlags);
186
+ TORCH_CHECK(
187
+ err == cudaSuccess,
188
+ "cudaStreamGetFlags failed: ",
189
+ cudaGetErrorString(err));
190
+
191
+ NppiSize oSizeROI = {frameDims.width, frameDims.height};
192
+ Npp8u* yuvData[2] = {avFrame->data[0], avFrame->data[1]};
193
+
194
+ NppStatus status;
195
+
196
+ // For background, see
197
+ // Note [YUV -> RGB Color Conversion, color space and color range]
198
+ if (avFrame->colorspace == AVColorSpace::AVCOL_SPC_BT709) {
199
+ if (avFrame->color_range == AVColorRange::AVCOL_RANGE_JPEG) {
200
+ // NPP provides a pre-defined color conversion function for BT.709 full
201
+ // range: nppiNV12ToRGB_709HDTV_8u_P2C3R_Ctx. But it's not closely
202
+ // matching the results we have on CPU. So we're using a custom color
203
+ // conversion matrix, which provides more accurate results. See the note
204
+ // mentioned above for details, and headaches.
205
+
206
+ int srcStep[2] = {avFrame->linesize[0], avFrame->linesize[1]};
207
+
208
+ status = nppiNV12ToRGB_8u_ColorTwist32f_P2C3R_Ctx(
209
+ yuvData,
210
+ srcStep,
211
+ static_cast<Npp8u*>(dst.data_ptr()),
212
+ dst.stride(0),
213
+ oSizeROI,
214
+ bt709FullRangeColorTwist,
215
+ *nppCtx);
216
+ } else {
217
+ // If not full range, we assume studio limited range.
218
+ // The color conversion matrix for BT.709 limited range should be:
219
+ // static const Npp32f bt709LimitedRangeColorTwist[3][4] = {
220
+ // {1.16438356f, 0.0f, 1.79274107f, -16.0f},
221
+ // {1.16438356f, -0.213248614f, -0.5329093290f, -128.0f},
222
+ // {1.16438356f, 2.11240179f, 0.0f, -128.0f}
223
+ // };
224
+ // We get very close results to CPU with that, but using the pre-defined
225
+ // nppiNV12ToRGB_709CSC_8u_P2C3R_Ctx seems to be even more accurate.
226
+ status = nppiNV12ToRGB_709CSC_8u_P2C3R_Ctx(
227
+ yuvData,
228
+ avFrame->linesize[0],
229
+ static_cast<Npp8u*>(dst.data_ptr()),
230
+ dst.stride(0),
231
+ oSizeROI,
232
+ *nppCtx);
233
+ }
234
+ } else {
235
+ // TODO we're assuming BT.601 color space (and probably limited range) by
236
+ // calling nppiNV12ToRGB_8u_P2C3R_Ctx. We should handle BT.601 full range,
237
+ // and other color-spaces like 2020.
238
+ status = nppiNV12ToRGB_8u_P2C3R_Ctx(
239
+ yuvData,
240
+ avFrame->linesize[0],
241
+ static_cast<Npp8u*>(dst.data_ptr()),
242
+ dst.stride(0),
243
+ oSizeROI,
244
+ *nppCtx);
245
+ }
246
+ TORCH_CHECK(status == NPP_SUCCESS, "Failed to convert NV12 frame.");
247
+
248
+ return dst;
249
+ }
250
+
251
+ UniqueNppContext getNppStreamContext(const torch::Device& device) {
252
+ torch::DeviceIndex nonNegativeDeviceIndex = getNonNegativeDeviceIndex(device);
253
+
254
+ UniqueNppContext nppCtx = g_cached_npp_ctxs.get(device);
255
+ if (nppCtx) {
256
+ return nppCtx;
257
+ }
258
+
259
+ // From 12.9, NPP recommends using a user-created NppStreamContext and using
260
+ // the `_Ctx()` calls:
261
+ // https://docs.nvidia.com/cuda/cuda-toolkit-release-notes/index.html#npp-release-12-9-update-1
262
+ // And the nppGetStreamContext() helper is deprecated. We are explicitly
263
+ // supposed to create the NppStreamContext manually from the CUDA device
264
+ // properties:
265
+ // https://github.com/NVIDIA/CUDALibrarySamples/blob/d97803a40fab83c058bb3d68b6c38bd6eebfff43/NPP/README.md?plain=1#L54-L72
266
+
267
+ nppCtx = std::make_unique<NppStreamContext>();
268
+ cudaDeviceProp prop{};
269
+ cudaError_t err = cudaGetDeviceProperties(&prop, nonNegativeDeviceIndex);
270
+ TORCH_CHECK(
271
+ err == cudaSuccess,
272
+ "cudaGetDeviceProperties failed: ",
273
+ cudaGetErrorString(err));
274
+
275
+ nppCtx->nCudaDeviceId = nonNegativeDeviceIndex;
276
+ nppCtx->nMultiProcessorCount = prop.multiProcessorCount;
277
+ nppCtx->nMaxThreadsPerMultiProcessor = prop.maxThreadsPerMultiProcessor;
278
+ nppCtx->nMaxThreadsPerBlock = prop.maxThreadsPerBlock;
279
+ nppCtx->nSharedMemPerBlock = prop.sharedMemPerBlock;
280
+ nppCtx->nCudaDevAttrComputeCapabilityMajor = prop.major;
281
+ nppCtx->nCudaDevAttrComputeCapabilityMinor = prop.minor;
282
+
283
+ return nppCtx;
284
+ }
285
+
286
+ void returnNppStreamContextToCache(
287
+ const torch::Device& device,
288
+ UniqueNppContext nppCtx) {
289
+ if (nppCtx) {
290
+ g_cached_npp_ctxs.addIfCacheHasCapacity(device, std::move(nppCtx));
291
+ }
292
+ }
293
+
294
+ void validatePreAllocatedTensorShape(
295
+ const std::optional<torch::Tensor>& preAllocatedOutputTensor,
296
+ const UniqueAVFrame& avFrame) {
297
+ // Note that CUDA does not yet support transforms, so the only possible
298
+ // frame dimensions are the raw decoded frame's dimensions.
299
+ auto frameDims = FrameDims(avFrame->height, avFrame->width);
300
+
301
+ if (preAllocatedOutputTensor.has_value()) {
302
+ auto shape = preAllocatedOutputTensor.value().sizes();
303
+ TORCH_CHECK(
304
+ (shape.size() == 3) && (shape[0] == frameDims.height) &&
305
+ (shape[1] == frameDims.width) && (shape[2] == 3),
306
+ "Expected tensor of shape ",
307
+ frameDims.height,
308
+ "x",
309
+ frameDims.width,
310
+ "x3, got ",
311
+ shape);
312
+ }
313
+ }
314
+
315
+ } // namespace facebook::torchcodec
@@ -0,0 +1,46 @@
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
+ #pragma once
8
+
9
+ #include <ATen/cuda/CUDAEvent.h>
10
+ #include <c10/cuda/CUDAStream.h>
11
+ #include <npp.h>
12
+ #include <torch/types.h>
13
+
14
+ #include "src/torchcodec/_core/Cache.h"
15
+ #include "src/torchcodec/_core/FFMPEGCommon.h"
16
+ #include "src/torchcodec/_core/Frame.h"
17
+
18
+ extern "C" {
19
+ #include <libavutil/hwcontext_cuda.h>
20
+ #include <libavutil/pixdesc.h>
21
+ }
22
+
23
+ namespace facebook::torchcodec {
24
+
25
+ void initializeCudaContextWithPytorch(const torch::Device& device);
26
+
27
+ // Unique pointer type for NPP stream context
28
+ using UniqueNppContext = std::unique_ptr<NppStreamContext>;
29
+
30
+ torch::Tensor convertNV12FrameToRGB(
31
+ UniqueAVFrame& avFrame,
32
+ const torch::Device& device,
33
+ const UniqueNppContext& nppCtx,
34
+ at::cuda::CUDAStream nvdecStream,
35
+ std::optional<torch::Tensor> preAllocatedOutputTensor = std::nullopt);
36
+
37
+ UniqueNppContext getNppStreamContext(const torch::Device& device);
38
+ void returnNppStreamContextToCache(
39
+ const torch::Device& device,
40
+ UniqueNppContext nppCtx);
41
+
42
+ void validatePreAllocatedTensorShape(
43
+ const std::optional<torch::Tensor>& preAllocatedOutputTensor,
44
+ const UniqueAVFrame& avFrame);
45
+
46
+ } // namespace facebook::torchcodec