torchcodec 1.0.0__py3-none-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.
Files changed (179) hide show
  1. torchcodec/__init__.py +50 -0
  2. torchcodec/_core/AVIOContextHolder.cpp +85 -0
  3. torchcodec/_core/AVIOContextHolder.h +44 -0
  4. torchcodec/_core/AudioCommon.cpp +101 -0
  5. torchcodec/_core/AudioCommon.h +48 -0
  6. torchcodec/_core/AudioConverter.cpp +130 -0
  7. torchcodec/_core/AudioConverter.h +59 -0
  8. torchcodec/_core/BetaCudaDeviceInterface.cpp +1635 -0
  9. torchcodec/_core/BetaCudaDeviceInterface.h +364 -0
  10. torchcodec/_core/CMakeLists.txt +661 -0
  11. torchcodec/_core/CUDACommon.cpp +129 -0
  12. torchcodec/_core/CUDACommon.h +115 -0
  13. torchcodec/_core/Cache.h +126 -0
  14. torchcodec/_core/CodecParameters.cpp +98 -0
  15. torchcodec/_core/CodecParameters.h +59 -0
  16. torchcodec/_core/ColorConverter.cpp +92 -0
  17. torchcodec/_core/ColorConverter.h +40 -0
  18. torchcodec/_core/CpuDeviceInterface.cpp +654 -0
  19. torchcodec/_core/CpuDeviceInterface.h +153 -0
  20. torchcodec/_core/CudaDeviceInterface.cpp +519 -0
  21. torchcodec/_core/CudaDeviceInterface.h +92 -0
  22. torchcodec/_core/DecodeAvif.cpp +284 -0
  23. torchcodec/_core/DecodeAvif.h +28 -0
  24. torchcodec/_core/DecodeGif.cpp +488 -0
  25. torchcodec/_core/DecodeGif.h +32 -0
  26. torchcodec/_core/DecodeHeic.cpp +306 -0
  27. torchcodec/_core/DecodeHeic.h +18 -0
  28. torchcodec/_core/DecodeJpeg.cpp +489 -0
  29. torchcodec/_core/DecodeJpeg.h +17 -0
  30. torchcodec/_core/DecodeJpegCuda.cpp +638 -0
  31. torchcodec/_core/DecodeJpegCuda.h +92 -0
  32. torchcodec/_core/DecodePng.cpp +569 -0
  33. torchcodec/_core/DecodePng.h +31 -0
  34. torchcodec/_core/DecodeWebp.cpp +238 -0
  35. torchcodec/_core/DecodeWebp.h +17 -0
  36. torchcodec/_core/Demuxer.cpp +415 -0
  37. torchcodec/_core/Demuxer.h +158 -0
  38. torchcodec/_core/DeviceInterface.cpp +152 -0
  39. torchcodec/_core/DeviceInterface.h +255 -0
  40. torchcodec/_core/EncodeJpeg.cpp +223 -0
  41. torchcodec/_core/EncodeJpeg.h +19 -0
  42. torchcodec/_core/EncodeJpegCuda.cpp +272 -0
  43. torchcodec/_core/EncodeJpegCuda.h +56 -0
  44. torchcodec/_core/EncodePng.cpp +207 -0
  45. torchcodec/_core/EncodePng.h +19 -0
  46. torchcodec/_core/Encoder.cpp +1023 -0
  47. torchcodec/_core/Encoder.h +144 -0
  48. torchcodec/_core/Exif.h +241 -0
  49. torchcodec/_core/FFMPEGCommon.cpp +1159 -0
  50. torchcodec/_core/FFMPEGCommon.h +506 -0
  51. torchcodec/_core/FileIO.cpp +78 -0
  52. torchcodec/_core/FileIO.h +34 -0
  53. torchcodec/_core/FileLikeIO.cpp +76 -0
  54. torchcodec/_core/FileLikeIO.h +68 -0
  55. torchcodec/_core/FilterGraph.cpp +211 -0
  56. torchcodec/_core/FilterGraph.h +59 -0
  57. torchcodec/_core/Frame.cpp +75 -0
  58. torchcodec/_core/Frame.h +76 -0
  59. torchcodec/_core/IOInterface.h +44 -0
  60. torchcodec/_core/ImageCommon.h +113 -0
  61. torchcodec/_core/Logging.cpp +42 -0
  62. torchcodec/_core/Logging.h +38 -0
  63. torchcodec/_core/Metadata.cpp +312 -0
  64. torchcodec/_core/Metadata.h +115 -0
  65. torchcodec/_core/NVCUVIDRuntimeLoader.cpp +324 -0
  66. torchcodec/_core/NVCUVIDRuntimeLoader.h +14 -0
  67. torchcodec/_core/NVDECCache.cpp +111 -0
  68. torchcodec/_core/NVDECCache.h +136 -0
  69. torchcodec/_core/NVDECCacheConfig.cpp +61 -0
  70. torchcodec/_core/NVDECCacheConfig.h +30 -0
  71. torchcodec/_core/PacketDecoder.cpp +358 -0
  72. torchcodec/_core/PacketDecoder.h +140 -0
  73. torchcodec/_core/SingleStreamDecoder.cpp +1856 -0
  74. torchcodec/_core/SingleStreamDecoder.h +424 -0
  75. torchcodec/_core/StableABICompat.h +213 -0
  76. torchcodec/_core/StreamOptions.h +93 -0
  77. torchcodec/_core/SwScale.cpp +124 -0
  78. torchcodec/_core/SwScale.h +67 -0
  79. torchcodec/_core/TensorIO.cpp +136 -0
  80. torchcodec/_core/TensorIO.h +53 -0
  81. torchcodec/_core/Transform.cpp +207 -0
  82. torchcodec/_core/Transform.h +125 -0
  83. torchcodec/_core/ValidationUtils.cpp +65 -0
  84. torchcodec/_core/ValidationUtils.h +29 -0
  85. torchcodec/_core/WavDecoder.cpp +494 -0
  86. torchcodec/_core/WavDecoder.h +73 -0
  87. torchcodec/_core/__init__.py +45 -0
  88. torchcodec/_core/_decoder_utils.py +258 -0
  89. torchcodec/_core/_ffmpeg_op_names.py +95 -0
  90. torchcodec/_core/_ffmpeg_ops.py +699 -0
  91. torchcodec/_core/_file_like.py +221 -0
  92. torchcodec/_core/_metadata.py +402 -0
  93. torchcodec/_core/color_conversion.cpp +316 -0
  94. torchcodec/_core/color_conversion.cu +391 -0
  95. torchcodec/_core/color_conversion.h +150 -0
  96. torchcodec/_core/custom_ops.cpp +2438 -0
  97. torchcodec/_core/fetch_and_expose_non_gpl_ffmpeg_libs.cmake +192 -0
  98. torchcodec/_core/fetch_avif_from_s3.cmake +81 -0
  99. torchcodec/_core/giflib/README +28 -0
  100. torchcodec/_core/giflib/dgif_lib.c +1313 -0
  101. torchcodec/_core/giflib/gif_hash.c +129 -0
  102. torchcodec/_core/giflib/gif_hash.h +43 -0
  103. torchcodec/_core/giflib/gif_lib.h +292 -0
  104. torchcodec/_core/giflib/gif_lib_private.h +73 -0
  105. torchcodec/_core/giflib/gifalloc.c +426 -0
  106. torchcodec/_core/giflib/openbsd-reallocarray.c +74 -0
  107. torchcodec/_core/heic_custom_ops.cpp +20 -0
  108. torchcodec/_core/image_custom_ops.cpp +137 -0
  109. torchcodec/_core/nvcuvid_include/cuviddec.h +1374 -0
  110. torchcodec/_core/nvcuvid_include/nvcuvid.h +610 -0
  111. torchcodec/_core/ops.py +103 -0
  112. torchcodec/_core/sources.bzl +113 -0
  113. torchcodec/_frame.py +146 -0
  114. torchcodec/_internally_replaced_utils.py +129 -0
  115. torchcodec/_logging.py +59 -0
  116. torchcodec/decoders/__init__.py +50 -0
  117. torchcodec/decoders/_audio_decoder.py +183 -0
  118. torchcodec/decoders/_blocks/__init__.py +48 -0
  119. torchcodec/decoders/_blocks/_audio_converter.py +155 -0
  120. torchcodec/decoders/_blocks/_codec_parameters.py +229 -0
  121. torchcodec/decoders/_blocks/_color_converter.py +107 -0
  122. torchcodec/decoders/_blocks/_demuxer.py +678 -0
  123. torchcodec/decoders/_blocks/_frame.py +577 -0
  124. torchcodec/decoders/_blocks/_helpers.py +53 -0
  125. torchcodec/decoders/_blocks/_packet_decoder.py +357 -0
  126. torchcodec/decoders/_decoder_utils.py +128 -0
  127. torchcodec/decoders/_image_decoders.py +1575 -0
  128. torchcodec/decoders/_video_decoder.py +592 -0
  129. torchcodec/decoders/_wav_decoder.py +131 -0
  130. torchcodec/encoders/__init__.py +4 -0
  131. torchcodec/encoders/_audio_encoder.py +167 -0
  132. torchcodec/encoders/_image_encoders.py +181 -0
  133. torchcodec/encoders/_multi_stream_encoder.py +272 -0
  134. torchcodec/encoders/_video_encoder.py +227 -0
  135. torchcodec/jpeg8.dll +0 -0
  136. torchcodec/libavif.dll +0 -0
  137. torchcodec/libpng16.dll +0 -0
  138. torchcodec/libsharpyuv.dll +0 -0
  139. torchcodec/libtorchcodec_core4.dll +0 -0
  140. torchcodec/libtorchcodec_core5.dll +0 -0
  141. torchcodec/libtorchcodec_core6.dll +0 -0
  142. torchcodec/libtorchcodec_core7.dll +0 -0
  143. torchcodec/libtorchcodec_core8.dll +0 -0
  144. torchcodec/libtorchcodec_core9.dll +0 -0
  145. torchcodec/libtorchcodec_custom_ops4.dll +0 -0
  146. torchcodec/libtorchcodec_custom_ops5.dll +0 -0
  147. torchcodec/libtorchcodec_custom_ops6.dll +0 -0
  148. torchcodec/libtorchcodec_custom_ops7.dll +0 -0
  149. torchcodec/libtorchcodec_custom_ops8.dll +0 -0
  150. torchcodec/libtorchcodec_custom_ops9.dll +0 -0
  151. torchcodec/libtorchcodec_heic.dll +0 -0
  152. torchcodec/libtorchcodec_image.dll +0 -0
  153. torchcodec/libwebp.dll +0 -0
  154. torchcodec/libwebpdecoder.dll +0 -0
  155. torchcodec/libwebpdemux.dll +0 -0
  156. torchcodec/libwebpmux.dll +0 -0
  157. torchcodec/libzstd.dll +0 -0
  158. torchcodec/py.typed +0 -0
  159. torchcodec/samplers/__init__.py +2 -0
  160. torchcodec/samplers/_common.py +83 -0
  161. torchcodec/samplers/_index_based.py +287 -0
  162. torchcodec/samplers/_time_based.py +360 -0
  163. torchcodec/share/cmake/TorchCodec/TorchCodecConfig.cmake +76 -0
  164. torchcodec/share/cmake/TorchCodec/ffmpeg_versions.cmake +128 -0
  165. torchcodec/transforms/__init__.py +12 -0
  166. torchcodec/transforms/_decoder_transforms.py +375 -0
  167. torchcodec/version.py +1 -0
  168. torchcodec/zlib.dll +0 -0
  169. torchcodec-1.0.0.dist-info/METADATA +275 -0
  170. torchcodec-1.0.0.dist-info/RECORD +179 -0
  171. torchcodec-1.0.0.dist-info/WHEEL +5 -0
  172. torchcodec-1.0.0.dist-info/licenses/LICENSE +28 -0
  173. torchcodec-1.0.0.dist-info/licenses/third_party/COPYING.dav1d +23 -0
  174. torchcodec-1.0.0.dist-info/licenses/third_party/LICENSE.libavif +387 -0
  175. torchcodec-1.0.0.dist-info/licenses/third_party/LICENSE.libjpeg-turbo +135 -0
  176. torchcodec-1.0.0.dist-info/licenses/third_party/LICENSE.libpng +134 -0
  177. torchcodec-1.0.0.dist-info/licenses/third_party/LICENSE.libwebp +30 -0
  178. torchcodec-1.0.0.dist-info/licenses/third_party/LICENSE.libyuv +29 -0
  179. torchcodec-1.0.0.dist-info/licenses/third_party/LICENSE.zlib +22 -0
@@ -0,0 +1,93 @@
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 <map>
10
+ #include <optional>
11
+ #include <string>
12
+ #include <string_view>
13
+ #include "StableABICompat.h"
14
+
15
+ namespace facebook::torchcodec {
16
+
17
+ enum ColorConversionLibrary {
18
+ // Use the libavfilter library for color conversion.
19
+ FILTERGRAPH,
20
+ // Use the libswscale library for color conversion.
21
+ SWSCALE
22
+ };
23
+
24
+ // The resolved output dtype. Only UINT8 or FLOAT32 — no AUTO.
25
+ // All code downstream of addVideoStream() should use this.
26
+ enum class OutputDtype { UINT8, FLOAT32 };
27
+
28
+ // The user-facing output dtype config, which may include AUTO.
29
+ // AUTO is resolved in addVideoStream() into an OutputDtype.
30
+ // UINT8: Always output uint8 tensors (default, backward compatible). Uses an
31
+ // 8-bit / RGB24 intermediate.
32
+ // FLOAT32: Always output float32 tensors normalized to [0, 1]. Uses a 16-bit /
33
+ // RGB48 intermediate so the YUV->RGB matrix output is preserved at
34
+ // full precision through the float cast, regardless of source bit
35
+ // depth.
36
+ // AUTO: Output uint8 for SDR (<=8-bit) sources, float32 for HDR (>8-bit).
37
+ enum class OutputDtypeConfig { UINT8, FLOAT32, AUTO };
38
+
39
+ struct VideoStreamOptions {
40
+ VideoStreamOptions() {}
41
+
42
+ // Number of threads we pass to FFMPEG for decoding.
43
+ // 0 means FFMPEG will choose the number of threads automatically to fully
44
+ // utilize all cores. If not set, it will be the default FFMPEG behavior for
45
+ // the given codec.
46
+ std::optional<int> ffmpeg_thread_count;
47
+
48
+ // Currently the dimension order can be either NHWC or NCHW.
49
+ // H=height, W=width, C=channel.
50
+ std::string dimension_order = "NCHW";
51
+
52
+ // By default we have to use filtergraph, as it is more general. We can only
53
+ // use swscale when we have met strict requirements. See
54
+ // CpuDeviceInterface::initialze() for the logic.
55
+ ColorConversionLibrary color_conversion_library =
56
+ ColorConversionLibrary::FILTERGRAPH;
57
+
58
+ // By default we use CPU for decoding for both C++ and python users.
59
+ // Note: This is not used for video encoding, because device is determined by
60
+ // the device of the input frame tensor.
61
+ StableDevice device = StableDevice(kStableCPU);
62
+ // Device variant (e.g., "nvdec", "ffmpeg")
63
+ std::string_view device_variant = "default";
64
+
65
+ // The user-specified output dtype config. May be AUTO, which gets resolved
66
+ // in addVideoStream() into outputDtype below.
67
+ OutputDtypeConfig output_dtype_config = OutputDtypeConfig::UINT8;
68
+
69
+ // Set by addVideoStream() after resolving AUTO. All downstream code should
70
+ // read this field.
71
+ OutputDtype output_dtype = OutputDtype::UINT8;
72
+
73
+ // Encoding options
74
+ std::optional<std::string> codec;
75
+ // Optional pixel format for video encoding (e.g., "yuv420p", "yuv444p")
76
+ // If not specified, uses codec's default format.
77
+ std::optional<std::string> pixel_format;
78
+ std::optional<double> crf;
79
+ std::optional<std::string> preset;
80
+ std::optional<std::map<std::string, std::string>> extra_options;
81
+ };
82
+
83
+ struct AudioStreamOptions {
84
+ AudioStreamOptions() {}
85
+
86
+ // Encoding only
87
+ std::optional<int> bit_rate;
88
+ // Decoding and encoding:
89
+ std::optional<int> num_channels;
90
+ std::optional<int> sample_rate;
91
+ };
92
+
93
+ } // namespace facebook::torchcodec
@@ -0,0 +1,124 @@
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 "SwScale.h"
8
+ #include "Frame.h"
9
+
10
+ namespace facebook::torchcodec {
11
+
12
+ SwScale::SwScale(const SwsConfig& config, int sws_flags)
13
+ : config_(config), sws_flags_(sws_flags) {
14
+ needs_resize_ =
15
+ (config_.input_height != config_.output_height ||
16
+ config_.input_width != config_.output_width);
17
+
18
+ // Create color conversion context (input format -> output RGB format).
19
+ // Color conversion always outputs at the input resolution.
20
+ // When no resize is needed, input and output resolutions are the same.
21
+ // See [Transform and Format Conversion Order] for more on the output pixel
22
+ // format.
23
+ SwsConfig color_conversion_frame_config{
24
+ .input_width = config_.input_width,
25
+ .input_height = config_.input_height,
26
+ .input_format = config_.input_format,
27
+ .input_colorspace = config_.input_colorspace,
28
+ .input_color_range = config_.input_color_range,
29
+ .output_width = config_.input_width,
30
+ .output_height = config_.input_height,
31
+ .output_format = config_.output_format};
32
+
33
+ color_conversion_sws_context_ = create_sws_context(
34
+ color_conversion_frame_config,
35
+ // No flags for color conversion. When resizing is needed, we use a
36
+ // separate swscale context with the appropriate resize flags.
37
+ /*swsFlags=*/0);
38
+
39
+ // Create resize context if needed (output RGB at input resolution ->
40
+ // output RGB at output resolution).
41
+ if (needs_resize_) {
42
+ SwsConfig resize_frame_config{
43
+ .input_width = config_.input_width,
44
+ .input_height = config_.input_height,
45
+ .input_format = config_.output_format,
46
+ .input_colorspace = AVCOL_SPC_RGB,
47
+ .output_width = config_.output_width,
48
+ .output_height = config_.output_height,
49
+ .output_format = config_.output_format};
50
+
51
+ resize_sws_context_ = create_sws_context(resize_frame_config, sws_flags_);
52
+
53
+ color_converted_frame_.reset(av_frame_alloc());
54
+ STD_TORCH_CHECK(
55
+ color_converted_frame_ != nullptr, "Failed to allocate AVFrame");
56
+ color_converted_frame_->format = config_.output_format;
57
+ color_converted_frame_->width = config_.input_width;
58
+ color_converted_frame_->height = config_.input_height;
59
+ int status = av_frame_get_buffer(color_converted_frame_.get(), 0);
60
+ STD_TORCH_CHECK(
61
+ status == 0,
62
+ "Failed to allocate color conversion buffer: ",
63
+ get_ffmpeg_error_string_from_error_code(status));
64
+ }
65
+ }
66
+
67
+ int SwScale::convert(
68
+ const AVFrame& av_frame,
69
+ torch::stable::Tensor& output_tensor) {
70
+ // When resizing is needed, we do sws_scale twice: first convert to output
71
+ // RGB at original resolution, then resize in output RGB space. This ensures
72
+ // transforms happen in the output color space (RGB) rather than the input
73
+ // color space (YUV).
74
+ //
75
+ // When no resize is needed, we do color conversion directly into the output
76
+ // tensor.
77
+ // RGB24 = 3 channels x 1 byte (uint8); RGB48 = 3 channels x 2 bytes (uint16).
78
+ bool is_rgb48 = config_.output_format == AV_PIX_FMT_RGB48;
79
+ int bytes_per_pixel = is_rgb48 ? 6 : 3;
80
+
81
+ // sws_scale always takes uint8_t* pointers regardless of actual bit depth.
82
+ uint8_t* output_pointers[4] = {
83
+ static_cast<uint8_t*>(output_tensor.mutable_data_ptr()),
84
+ nullptr,
85
+ nullptr,
86
+ nullptr};
87
+ int output_linesizes[4] = {config_.output_width * bytes_per_pixel, 0, 0, 0};
88
+
89
+ uint8_t* const* color_converted_pointers =
90
+ needs_resize_ ? color_converted_frame_->data : output_pointers;
91
+ const int* color_converted_linesizes =
92
+ needs_resize_ ? color_converted_frame_->linesize : output_linesizes;
93
+
94
+ int color_converted_height = sws_scale(
95
+ color_conversion_sws_context_.get(),
96
+ av_frame.data,
97
+ av_frame.linesize,
98
+ 0,
99
+ av_frame.height,
100
+ color_converted_pointers,
101
+ color_converted_linesizes);
102
+
103
+ STD_TORCH_CHECK(
104
+ color_converted_height == av_frame.height,
105
+ "Color conversion swscale pass failed: colorConvertedHeight != avFrame->height: ",
106
+ color_converted_height,
107
+ " != ",
108
+ av_frame.height);
109
+
110
+ if (needs_resize_) {
111
+ color_converted_height = sws_scale(
112
+ resize_sws_context_.get(),
113
+ color_converted_frame_->data,
114
+ color_converted_frame_->linesize,
115
+ 0,
116
+ config_.input_height,
117
+ output_pointers,
118
+ output_linesizes);
119
+ }
120
+
121
+ return color_converted_height;
122
+ }
123
+
124
+ } // namespace facebook::torchcodec
@@ -0,0 +1,67 @@
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 "FFMPEGCommon.h"
10
+ #include "StableABICompat.h"
11
+
12
+ namespace facebook::torchcodec {
13
+
14
+ struct FrameDims;
15
+
16
+ // SwScale uses a double swscale path:
17
+ // 1. Color conversion (e.g., YUV -> RGB24/RGB48) at the original frame
18
+ // resolution
19
+ // 2. Resize in output RGB space (if resizing is needed)
20
+ //
21
+ // This approach ensures that transforms happen in the output color space
22
+ // (RGB) rather than the input color space (YUV).
23
+ //
24
+ // The caller is responsible for caching SwScale instances and recreating them
25
+ // when the context changes, similar to how FilterGraph is managed.
26
+ class SwScale {
27
+ public:
28
+ // config.outputFormat is AV_PIX_FMT_RGB24 for 8-bit, AV_PIX_FMT_RGB48 for
29
+ // >8-bit.
30
+ SwScale(const SwsConfig& config, int sws_flags = SWS_BILINEAR);
31
+
32
+ int convert(const AVFrame& av_frame, torch::stable::Tensor& output_tensor);
33
+
34
+ const SwsConfig& get_config() const {
35
+ return config_;
36
+ }
37
+
38
+ private:
39
+ SwsConfig config_;
40
+ int sws_flags_;
41
+ bool needs_resize_;
42
+
43
+ // Color conversion context (input format -> output RGB at original
44
+ // resolution).
45
+ UniqueSwsContext color_conversion_sws_context_;
46
+
47
+ // Resize context (output RGB at input res -> output RGB at output res).
48
+ // May be null if no resize is needed.
49
+ UniqueSwsContext resize_sws_context_;
50
+
51
+ // Scratch buffer holding the result of the color conversion, which is then
52
+ // the input of the resize. Null if no resize is needed.
53
+ // This must be an AVFrame allocated by FFmpeg. We used to allocate this
54
+ // ourselves as a tensor, but that could cause a crash in some rare cases:
55
+ // swscale may read **past** the source passed to sws_scale() when it's using
56
+ // SIMD ops. It typically reads past the linesize on each row, which is fine
57
+ // for all rows except the last one, where this is at best UB, at worst a
58
+ // segfault. IMHO this qualifies as a bug in swscale, and FWIW we fixed the
59
+ // exact same familiy of bugs in torch
60
+ // https://github.com/pytorch/pytorch/pull/179814!
61
+ // There's no non-regression test for that because it'd be too difficult to
62
+ // trigger, but context can be found in D120434423 and
63
+ // https://fburl.com/phabricator/7yqql5lj.
64
+ UniqueAVFrame color_converted_frame_;
65
+ };
66
+
67
+ } // namespace facebook::torchcodec
@@ -0,0 +1,136 @@
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 "TensorIO.h"
8
+ #include "StableABICompat.h"
9
+
10
+ namespace facebook::torchcodec {
11
+
12
+ namespace {
13
+ constexpr int64_t INITIAL_TENSOR_SIZE = 10'000'000; // 10 MB
14
+ constexpr int64_t MAX_TENSOR_SIZE = 320'000'000; // 320 MB
15
+ } // namespace
16
+
17
+ // --------------------------------------------------------------------------
18
+ // TensorReadIO
19
+ // --------------------------------------------------------------------------
20
+
21
+ TensorReadIO::TensorReadIO(torch::stable::Tensor data)
22
+ : tensor_context_{data, 0, 0} {
23
+ STD_TORCH_CHECK(data.numel() > 0, "data must not be empty");
24
+ STD_TORCH_CHECK(data.is_contiguous(), "data must be contiguous");
25
+ STD_TORCH_CHECK(data.scalar_type() == kStableUInt8, "data must be kUInt8");
26
+ }
27
+
28
+ int TensorReadIO::read(uint8_t* buf, int size) {
29
+ if (tensor_context_.current_pos >= tensor_context_.data.numel()) {
30
+ return -1;
31
+ }
32
+
33
+ int64_t num_bytes_read = std::min(
34
+ static_cast<int64_t>(size),
35
+ tensor_context_.data.numel() - tensor_context_.current_pos);
36
+
37
+ STD_TORCH_CHECK(
38
+ num_bytes_read >= 0,
39
+ "Tried to read negative bytes: numBytesRead=",
40
+ num_bytes_read,
41
+ ", size=",
42
+ tensor_context_.data.numel(),
43
+ ", current_pos=",
44
+ tensor_context_.current_pos);
45
+
46
+ if (num_bytes_read == 0) {
47
+ return -1;
48
+ }
49
+
50
+ std::memcpy(
51
+ buf,
52
+ tensor_context_.data.const_data_ptr<uint8_t>() +
53
+ tensor_context_.current_pos,
54
+ num_bytes_read);
55
+ tensor_context_.current_pos += num_bytes_read;
56
+ return static_cast<int>(num_bytes_read);
57
+ }
58
+
59
+ int64_t TensorReadIO::seek(int64_t offset, int whence) {
60
+ switch (whence) {
61
+ case SEEK_SET:
62
+ tensor_context_.current_pos = offset;
63
+ return offset;
64
+ default:
65
+ return -1;
66
+ }
67
+ }
68
+
69
+ int64_t TensorReadIO::get_size() {
70
+ return tensor_context_.data.numel();
71
+ }
72
+
73
+ // --------------------------------------------------------------------------
74
+ // TensorWriteIO
75
+ // --------------------------------------------------------------------------
76
+
77
+ TensorWriteIO::TensorWriteIO()
78
+ : tensor_context_{
79
+ torch::stable::empty({INITIAL_TENSOR_SIZE}, kStableUInt8),
80
+ 0,
81
+ 0} {}
82
+
83
+ int TensorWriteIO::write(const uint8_t* buf, int size) {
84
+ int64_t buf_size = static_cast<int64_t>(size);
85
+ if (tensor_context_.current_pos + buf_size > tensor_context_.data.numel()) {
86
+ STD_TORCH_CHECK(
87
+ tensor_context_.data.numel() * 2 <= MAX_TENSOR_SIZE,
88
+ "We tried to allocate an output encoded tensor larger than ",
89
+ MAX_TENSOR_SIZE,
90
+ " bytes. If you think this should be supported, please report.");
91
+
92
+ // We double the size of the outpout tensor. Calling cat() may not be the
93
+ // most efficient, but it's simple.
94
+ tensor_context_.data =
95
+ stable_cat({tensor_context_.data, tensor_context_.data}, 0);
96
+ }
97
+
98
+ STD_TORCH_CHECK(
99
+ tensor_context_.current_pos + buf_size <= tensor_context_.data.numel(),
100
+ "Re-allocation of the output tensor didn't work. ",
101
+ "This should not happen, please report on TorchCodec bug tracker");
102
+
103
+ uint8_t* output_tensor_data =
104
+ tensor_context_.data.mutable_data_ptr<uint8_t>();
105
+ std::memcpy(output_tensor_data + tensor_context_.current_pos, buf, buf_size);
106
+ tensor_context_.current_pos += buf_size;
107
+ // Track the maximum position written so getOutputTensor's narrow() does not
108
+ // truncate the file if final seek was backwards
109
+ tensor_context_.max_pos =
110
+ std::max(tensor_context_.current_pos, tensor_context_.max_pos);
111
+ return size;
112
+ }
113
+
114
+ int64_t TensorWriteIO::seek(int64_t offset, int whence) {
115
+ switch (whence) {
116
+ case SEEK_SET:
117
+ tensor_context_.current_pos = offset;
118
+ return offset;
119
+ default:
120
+ return -1;
121
+ }
122
+ }
123
+
124
+ int64_t TensorWriteIO::get_size() {
125
+ return tensor_context_.data.numel();
126
+ }
127
+
128
+ torch::stable::Tensor TensorWriteIO::get_output_tensor() {
129
+ return torch::stable::narrow(
130
+ tensor_context_.data,
131
+ /*dim=*/0,
132
+ /*start=*/0,
133
+ /*length=*/tensor_context_.max_pos);
134
+ }
135
+
136
+ } // namespace facebook::torchcodec
@@ -0,0 +1,53 @@
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 "IOInterface.h"
10
+ #include "StableABICompat.h"
11
+
12
+ namespace facebook::torchcodec {
13
+
14
+ namespace detail {
15
+
16
+ struct TensorContext {
17
+ torch::stable::Tensor data;
18
+ int64_t current_pos;
19
+ int64_t max_pos;
20
+ };
21
+
22
+ } // namespace detail
23
+
24
+ // For decoding: reads/seeks over an entire video or audio passed in as a bytes
25
+ // tensor. FFmpeg-free.
26
+ class FORCE_PUBLIC_VISIBILITY TensorReadIO : public IOInterface {
27
+ public:
28
+ explicit TensorReadIO(torch::stable::Tensor data);
29
+
30
+ int read(uint8_t* buf, int size) override;
31
+ int64_t seek(int64_t offset, int whence) override;
32
+ int64_t get_size() override;
33
+
34
+ private:
35
+ detail::TensorContext tensor_context_;
36
+ };
37
+
38
+ // For encoding: writes into a growable output uint8 (bytes) tensor.
39
+ // FFmpeg-free.
40
+ class FORCE_PUBLIC_VISIBILITY TensorWriteIO : public IOInterface {
41
+ public:
42
+ explicit TensorWriteIO();
43
+ torch::stable::Tensor get_output_tensor();
44
+
45
+ int write(const uint8_t* buf, int size) override;
46
+ int64_t seek(int64_t offset, int whence) override;
47
+ int64_t get_size() override;
48
+
49
+ private:
50
+ detail::TensorContext tensor_context_;
51
+ };
52
+
53
+ } // namespace facebook::torchcodec
@@ -0,0 +1,207 @@
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 "Transform.h"
8
+ #include "FFMPEGCommon.h"
9
+ #include "StableABICompat.h"
10
+
11
+ namespace facebook::torchcodec {
12
+
13
+ namespace {
14
+
15
+ std::string to_filter_graph_interpolation(
16
+ ResizeTransform::InterpolationMode mode) {
17
+ switch (mode) {
18
+ case ResizeTransform::InterpolationMode::BILINEAR:
19
+ return "bilinear";
20
+ default:
21
+ STD_TORCH_CHECK(
22
+ false,
23
+ "Unknown interpolation mode: " +
24
+ std::to_string(static_cast<int>(mode)));
25
+ }
26
+ }
27
+
28
+ int to_sws_interpolation(ResizeTransform::InterpolationMode mode) {
29
+ switch (mode) {
30
+ case ResizeTransform::InterpolationMode::BILINEAR:
31
+ return SWS_BILINEAR;
32
+ default:
33
+ STD_TORCH_CHECK(
34
+ false,
35
+ "Unknown interpolation mode: " +
36
+ std::to_string(static_cast<int>(mode)));
37
+ }
38
+ }
39
+
40
+ } // namespace
41
+
42
+ std::string ResizeTransform::get_filter_graph_cpu() const {
43
+ return "scale=" + std::to_string(output_dims_.width) + ":" +
44
+ std::to_string(output_dims_.height) +
45
+ ":flags=" + to_filter_graph_interpolation(interpolation_mode_);
46
+ }
47
+
48
+ std::optional<FrameDims> ResizeTransform::get_output_frame_dims() const {
49
+ return output_dims_;
50
+ }
51
+
52
+ bool ResizeTransform::is_resize() const {
53
+ return true;
54
+ }
55
+
56
+ int ResizeTransform::get_sws_flags() const {
57
+ return to_sws_interpolation(interpolation_mode_);
58
+ }
59
+
60
+ CropTransform::CropTransform(const FrameDims& dims) : output_dims_(dims) {}
61
+
62
+ CropTransform::CropTransform(const FrameDims& dims, int x, int y)
63
+ : output_dims_(dims), x_(x), y_(y) {
64
+ STD_TORCH_CHECK(x >= 0, "Crop x position must be >= 0, got: ", x);
65
+ STD_TORCH_CHECK(y >= 0, "Crop y position must be >= 0, got: ", y);
66
+ }
67
+
68
+ std::string CropTransform::get_filter_graph_cpu() const {
69
+ // For the FFmpeg filter crop, if the x and y coordinates are left
70
+ // unspecified, it defaults to a center crop.
71
+ std::string coordinates = x_.has_value()
72
+ ? (":" + std::to_string(x_.value()) + ":" + std::to_string(y_.value()))
73
+ : "";
74
+ return "crop=" + std::to_string(output_dims_.width) + ":" +
75
+ std::to_string(output_dims_.height) + coordinates + ":exact=1";
76
+ }
77
+
78
+ std::optional<FrameDims> CropTransform::get_output_frame_dims() const {
79
+ return output_dims_;
80
+ }
81
+
82
+ void CropTransform::validate(const FrameDims& input_dims) const {
83
+ STD_TORCH_CHECK(
84
+ output_dims_.height <= input_dims.height,
85
+ "Crop output height (",
86
+ output_dims_.height,
87
+ ") is greater than input height (",
88
+ input_dims.height,
89
+ ")");
90
+ STD_TORCH_CHECK(
91
+ output_dims_.width <= input_dims.width,
92
+ "Crop output width (",
93
+ output_dims_.width,
94
+ ") is greater than input width (",
95
+ input_dims.width,
96
+ ")");
97
+ STD_TORCH_CHECK(
98
+ x_.has_value() == y_.has_value(),
99
+ "Crop x and y values must be both set or both unset");
100
+ if (x_.has_value()) {
101
+ STD_TORCH_CHECK(
102
+ x_.value() <= input_dims.width,
103
+ "Crop x start position, ",
104
+ x_.value(),
105
+ ", out of bounds of input width, ",
106
+ input_dims.width);
107
+ STD_TORCH_CHECK(
108
+ x_.value() + output_dims_.width <= input_dims.width,
109
+ "Crop x end position, ",
110
+ x_.value() + output_dims_.width,
111
+ ", out of bounds of input width ",
112
+ input_dims.width);
113
+ STD_TORCH_CHECK(
114
+ y_.value() <= input_dims.height,
115
+ "Crop y start position, ",
116
+ y_.value(),
117
+ ", out of bounds of input height, ",
118
+ input_dims.height);
119
+ STD_TORCH_CHECK(
120
+ y_.value() + output_dims_.height <= input_dims.height,
121
+ "Crop y end position, ",
122
+ y_.value() + output_dims_.height,
123
+ ", out of bounds of input height ",
124
+ input_dims.height);
125
+ }
126
+ }
127
+
128
+ Rotation rotation_from_degrees(std::optional<double> degrees) {
129
+ if (!degrees.has_value()) {
130
+ return Rotation::NONE;
131
+ }
132
+ // Round to nearest multiple of 90 degrees
133
+ int rounded = static_cast<int>(std::round(*degrees / 90.0)) * 90;
134
+ switch (rounded) {
135
+ case 0:
136
+ return Rotation::NONE;
137
+ case 90:
138
+ return Rotation::CCW90;
139
+ case -90:
140
+ return Rotation::CW90;
141
+ case 180:
142
+ case -180:
143
+ return Rotation::ROTATE180;
144
+ default:
145
+ STD_TORCH_CHECK(
146
+ false,
147
+ "Unexpected rotation value: ",
148
+ *degrees,
149
+ ". Expected range is [-180, 180].");
150
+ }
151
+ }
152
+
153
+ torch::stable::Tensor rotate_hwc_tensor(
154
+ const torch::stable::Tensor& hwc,
155
+ Rotation rotation) {
156
+ int k = 0;
157
+ switch (rotation) {
158
+ case Rotation::NONE:
159
+ return hwc;
160
+ case Rotation::CCW90:
161
+ k = 1;
162
+ break;
163
+ case Rotation::ROTATE180:
164
+ k = 2;
165
+ break;
166
+ case Rotation::CW90:
167
+ k = 3;
168
+ break;
169
+ default:
170
+ STD_TORCH_CHECK(false, "Unexpected rotation value");
171
+ }
172
+ // stable_rot90 returns a view, so we need to make it contiguous.
173
+ return torch::stable::contiguous(stable_rot90(hwc, k, 0, 1));
174
+ }
175
+
176
+ RotationTransform::RotationTransform(
177
+ Rotation rotation,
178
+ const FrameDims& input_dims)
179
+ : rotation_(rotation) {
180
+ // 90° rotations swap dimensions
181
+ if (rotation_ == Rotation::CCW90 || rotation_ == Rotation::CW90) {
182
+ output_dims_ = FrameDims(input_dims.width, input_dims.height);
183
+ } else {
184
+ output_dims_ = input_dims;
185
+ }
186
+ }
187
+
188
+ std::string RotationTransform::get_filter_graph_cpu() const {
189
+ switch (rotation_) {
190
+ case Rotation::NONE:
191
+ return "";
192
+ case Rotation::CCW90:
193
+ return "transpose=cclock";
194
+ case Rotation::CW90:
195
+ return "transpose=clock";
196
+ case Rotation::ROTATE180:
197
+ return "hflip,vflip";
198
+ default:
199
+ return "";
200
+ }
201
+ }
202
+
203
+ std::optional<FrameDims> RotationTransform::get_output_frame_dims() const {
204
+ return output_dims_;
205
+ }
206
+
207
+ } // namespace facebook::torchcodec