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,158 @@
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 <memory>
11
+ #include <optional>
12
+ #include <string>
13
+ #include <utility>
14
+ #include <vector>
15
+
16
+ #include "AVIOContextHolder.h"
17
+ #include "CodecParameters.h"
18
+ #include "FFMPEGCommon.h"
19
+ #include "StableABICompat.h"
20
+
21
+ namespace facebook::torchcodec {
22
+
23
+ // Reads the next packet belonging to active_stream_index from format_context
24
+ // into `packet`. Returns AVSUCCESS with `packet` filled, AVERROR_EOF at end of
25
+ // stream, or a negative error code otherwise. Shared by Demuxer and
26
+ // SingleStreamDecoder so the demux + stream-filter loop lives in one place.
27
+ int read_next_packet(
28
+ AVFormatContext* format_context,
29
+ int active_stream_index,
30
+ AVPacket& packet);
31
+
32
+ // Same, for a demuxer following more than one stream: the packet comes from
33
+ // whichever of `active_stream_indices` has the next one.
34
+ int read_next_packet(
35
+ AVFormatContext* format_context,
36
+ const std::vector<int>& active_stream_indices,
37
+ AVPacket& packet);
38
+
39
+ std::string get_seek_error_message(
40
+ const AVFormatContext* format_context,
41
+ int64_t desired_pts,
42
+ int status);
43
+
44
+ // One demuxed packet, as a scan records it before sorting.
45
+ //
46
+ // Deliberately the same name as SingleStreamDecoder::FrameInfo, which its own
47
+ // scan produces: these describe the same thing, one entry per frame of a
48
+ // stream, and differ only in how they say it - `duration` here against
49
+ // `next_pts` there, and the frame's index implicit in the vector position
50
+ // rather than stored. The two scans should probably be unified eventually;
51
+ // until then the shared name is the reminder.
52
+ struct FrameInfo {
53
+ int64_t pts;
54
+ int64_t duration;
55
+ bool is_key_frame;
56
+ };
57
+
58
+ // The frames of one stream, in presentation order: three parallel tensors of
59
+ // length N, plus the time base `pts` and `duration` are expressed in.
60
+ struct FrameIndex {
61
+ torch::stable::Tensor pts; // int64 [N]
62
+ torch::stable::Tensor duration; // int64 [N]
63
+ torch::stable::Tensor is_key_frame; // bool [N]
64
+ AVRational time_base;
65
+ };
66
+
67
+ // Demux building block: owns an AVFormatContext, follows one or more of its
68
+ // streams, and yields their (compressed) packets. Does no decoding. Not
69
+ // thread-safe.
70
+ class FORCE_PUBLIC_VISIBILITY Demuxer {
71
+ public:
72
+ // Both constructors open the container and probe it, without following any
73
+ // stream: add_stream() must be called before anything can be demuxed.
74
+ explicit Demuxer(const std::string& file_path);
75
+
76
+ explicit Demuxer(std::unique_ptr<AVIOContextHolder> avio_context_holder);
77
+
78
+ // Starts following a stream, and returns its index (absolute across all
79
+ // media types) together with its media type. Identify it by exactly one of
80
+ // `stream_index`, whose media type is then looked up and must be audio or
81
+ // video, or `media_type`, which follows the best stream of that type.
82
+ std::pair<int, AVMediaType> add_stream(
83
+ std::optional<int> stream_index = std::nullopt,
84
+ std::optional<AVMediaType> media_type = std::nullopt);
85
+
86
+ // int64 [K]: the index of every audio and video stream in the container, in
87
+ // container order. Anything else - subtitles, data, attachments - is left
88
+ // out: those can be seen in the metadata but cannot be followed. Raises if
89
+ // the container has nothing that can be demuxed at all.
90
+ torch::stable::Tensor get_audio_video_stream_indices() const;
91
+
92
+ // Returns the next packet of whichever followed stream has one, as a
93
+ // freshly-allocated packet, or a null packet at end of stream. Which stream
94
+ // it belongs to is on the packet itself, as `stream_index`.
95
+ UniqueAVPacket next_packet();
96
+
97
+ // Moves the *container*: every followed stream jumps, so every decoder fed by
98
+ // this demuxer must be reset. The target is resolved against `stream_index`,
99
+ // or against get_reference_stream() when it is left unspecified.
100
+ void seek(double seconds, std::optional<int> stream_index = std::nullopt);
101
+
102
+ // Demuxes one stream entirely, without decoding, and returns one entry per
103
+ // frame sorted by pts. Leaves the demuxer back at the start of the container.
104
+ //
105
+ // The demux pass this needs covers every followed video stream at once and
106
+ // happens only once per demuxer, so indexing a second stream costs no I/O.
107
+ // Only legal before the first packet is demuxed, which is what makes the
108
+ // rewind harmless: nothing has been fed to a decoder yet.
109
+ FrameIndex scan(std::optional<int> stream_index = std::nullopt);
110
+
111
+ // A copy of the codec parameters of the stream at `stream_index`, or of the
112
+ // only followed stream when it is left unspecified.
113
+ CodecParameters get_codec_parameters(
114
+ std::optional<int> stream_index = std::nullopt) const;
115
+
116
+ // The index passed in, validated, or the only followed stream when it is left
117
+ // unspecified.
118
+ int resolve_stream_index(std::optional<int> stream_index) const;
119
+
120
+ const std::vector<int>& active_stream_indices() const {
121
+ return active_stream_indices_;
122
+ }
123
+
124
+ const UniqueDecodingAVFormatContext& format_context() const {
125
+ return format_context_;
126
+ }
127
+
128
+ private:
129
+ void find_stream_info();
130
+ // Checks `stream_index` is in range and that it is an audio or video stream.
131
+ void validate_requested_stream(int stream_index);
132
+ // The stream a seek is resolved against when the caller doesn't name one:
133
+ // simply the first one that was added. A seek is resolved in a single
134
+ // stream's time base and lands on that stream's keyframes, so which one it is
135
+ // does matter - but picking by media type would make the default depend on
136
+ // what the container happens to hold, where first-added is the caller's own
137
+ // ordering. Pass a stream to seek() to override it.
138
+ AVStream* get_reference_stream() const;
139
+ // Phase one of a scan: read the container once, bucketing the packets of
140
+ // every followed video stream. Idempotent.
141
+ void scan_all_video_streams();
142
+
143
+ // Declared before format_context_ so that it outlives it: the format context
144
+ // reads through the AVIOContext this holds.
145
+ std::unique_ptr<AVIOContextHolder> avio_context_holder_;
146
+ UniqueDecodingAVFormatContext format_context_;
147
+ // In the order they were added. A handful of entries at most, so this is
148
+ // scanned linearly.
149
+ std::vector<int> active_stream_indices_;
150
+ bool has_demuxed_ = false;
151
+ // Filled by scan_all_video_streams(), keyed by stream index. Sorted lazily,
152
+ // per stream, by scan().
153
+ std::map<int, std::vector<FrameInfo>> scanned_packets_;
154
+ bool has_scanned_ = false;
155
+ AutoAVPacket auto_packet_;
156
+ };
157
+
158
+ } // namespace facebook::torchcodec
@@ -0,0 +1,152 @@
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 "DeviceInterface.h"
8
+ #include <map>
9
+ #include <mutex>
10
+ #include "StableABICompat.h"
11
+
12
+ namespace facebook::torchcodec {
13
+
14
+ namespace {
15
+ using DeviceInterfaceMap =
16
+ std::map<DeviceInterfaceKey, CreateDeviceInterfaceFn>;
17
+ static std::mutex g_interface_mutex;
18
+
19
+ DeviceInterfaceMap& get_device_map() {
20
+ static DeviceInterfaceMap device_map;
21
+ return device_map;
22
+ }
23
+
24
+ std::string get_device_type_string(const std::string& device) {
25
+ size_t pos = device.find(':');
26
+ if (pos == std::string::npos) {
27
+ return device;
28
+ }
29
+ return device.substr(0, pos);
30
+ }
31
+
32
+ // Parse device type from string (e.g., "cpu", "cuda")
33
+ // TODO_STABLE_ABI: we might need to support more device types, i.e. those from
34
+ // https://github.com/pytorch/pytorch/blob/main/torch/headeronly/core/DeviceType.h
35
+ // Ideally we'd remove this helper?
36
+ StableDeviceType parse_device_type(const std::string& device_type) {
37
+ if (device_type == "cpu") {
38
+ return kStableCPU;
39
+ } else if (device_type == "cuda") {
40
+ return kStableCUDA;
41
+ } else if (device_type == "xpu") {
42
+ return kStableXPU;
43
+ } else {
44
+ STD_TORCH_CHECK(false, "Unknown device type: ", device_type);
45
+ }
46
+ }
47
+
48
+ } // namespace
49
+
50
+ bool register_device_interface(
51
+ const DeviceInterfaceKey& key,
52
+ CreateDeviceInterfaceFn create_interface) {
53
+ std::scoped_lock lock(g_interface_mutex);
54
+ DeviceInterfaceMap& device_map = get_device_map();
55
+
56
+ STD_TORCH_CHECK(
57
+ device_map.find(key) == device_map.end(),
58
+ "Device interface already registered for device type ",
59
+ static_cast<int>(key.device_type),
60
+ " variant '",
61
+ key.variant,
62
+ "'");
63
+ device_map.insert({key, create_interface});
64
+
65
+ return true;
66
+ }
67
+
68
+ void validate_device_interface(
69
+ const std::string& device,
70
+ const std::string& variant) {
71
+ std::scoped_lock lock(g_interface_mutex);
72
+ std::string device_type = get_device_type_string(device);
73
+
74
+ DeviceInterfaceMap& device_map = get_device_map();
75
+
76
+ // Find device interface that matches device type and variant
77
+ StableDeviceType device_type_enum = parse_device_type(device_type);
78
+
79
+ auto device_interface = std::find_if(
80
+ device_map.begin(),
81
+ device_map.end(),
82
+ [&](const std::pair<DeviceInterfaceKey, CreateDeviceInterfaceFn>& arg) {
83
+ return arg.first.device_type == device_type_enum &&
84
+ arg.first.variant == variant;
85
+ });
86
+
87
+ STD_TORCH_CHECK(
88
+ device_interface != device_map.end(),
89
+ "Unsupported device: ",
90
+ device,
91
+ " (device type: ",
92
+ device_type,
93
+ ", variant: ",
94
+ variant,
95
+ ")");
96
+ }
97
+
98
+ std::unique_ptr<DeviceInterface> create_device_interface(
99
+ const StableDevice& device,
100
+ const std::string_view variant) {
101
+ DeviceInterfaceKey key(device.type(), variant);
102
+ std::scoped_lock lock(g_interface_mutex);
103
+ DeviceInterfaceMap& device_map = get_device_map();
104
+
105
+ auto it = device_map.find(key);
106
+ if (it != device_map.end()) {
107
+ return std::unique_ptr<DeviceInterface>(it->second(device));
108
+ }
109
+
110
+ STD_TORCH_CHECK(
111
+ false,
112
+ "No device interface found for device type: ",
113
+ static_cast<int>(device.type()),
114
+ " variant: '",
115
+ variant,
116
+ "'");
117
+ }
118
+
119
+ torch::stable::Tensor rgb_av_frame_to_tensor(const AVFrame& av_frame) {
120
+ auto format = static_cast<AVPixelFormat>(av_frame.format);
121
+ STD_TORCH_CHECK(
122
+ format == AV_PIX_FMT_RGB24 || format == AV_PIX_FMT_RGB48,
123
+ "Expected RGB24 or RGB48 format, got ",
124
+ (av_get_pix_fmt_name(format) ? av_get_pix_fmt_name(format) : "unknown"));
125
+
126
+ int height = av_frame.height;
127
+ int width = av_frame.width;
128
+ AVFrame* cloned_av_frame = av_frame_clone(&av_frame);
129
+
130
+ auto deleter = [cloned_av_frame](void*) {
131
+ UniqueAVFrame av_frame_to_delete(cloned_av_frame);
132
+ };
133
+
134
+ std::vector<int64_t> shape = {height, width, 3};
135
+
136
+ // RGB48 stores 2 bytes per channel (uint16); RGB24 stores 1 byte (uint8).
137
+ // linesize is in bytes, but torch strides are in elements, so divide.
138
+ int bytes_per_element = (format == AV_PIX_FMT_RGB48) ? 2 : 1;
139
+ auto dtype = (format == AV_PIX_FMT_RGB48) ? kStableUInt16 : kStableUInt8;
140
+ std::vector<int64_t> strides = {
141
+ cloned_av_frame->linesize[0] / bytes_per_element, 3, 1};
142
+
143
+ return torch::stable::from_blob(
144
+ cloned_av_frame->data[0],
145
+ shape,
146
+ strides,
147
+ StableDevice(kStableCPU),
148
+ dtype,
149
+ deleter);
150
+ }
151
+
152
+ } // namespace facebook::torchcodec
@@ -0,0 +1,255 @@
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 <functional>
10
+ #include <memory>
11
+ #include <stdexcept>
12
+ #include <string>
13
+ #include "CodecParameters.h"
14
+ #include "FFMPEGCommon.h"
15
+ #include "Frame.h"
16
+ #include "StableABICompat.h"
17
+ #include "StreamOptions.h"
18
+ #include "Transform.h"
19
+
20
+ namespace facebook::torchcodec {
21
+
22
+ // Key for device interface registration with device type + variant support
23
+ struct DeviceInterfaceKey {
24
+ StableDeviceType device_type;
25
+ std::string_view variant = "default"; // e.g., "default", "ffmpeg"
26
+
27
+ bool operator<(const DeviceInterfaceKey& other) const {
28
+ if (device_type != other.device_type) {
29
+ return device_type < other.device_type;
30
+ }
31
+ return variant < other.variant;
32
+ }
33
+
34
+ explicit DeviceInterfaceKey(StableDeviceType type) : device_type(type) {}
35
+
36
+ DeviceInterfaceKey(StableDeviceType type, const std::string_view& variant)
37
+ : device_type(type), variant(variant) {}
38
+ };
39
+
40
+ class DeviceInterface {
41
+ public:
42
+ DeviceInterface(const StableDevice& device) : device_(device) {}
43
+
44
+ virtual ~DeviceInterface(){};
45
+
46
+ StableDevice& device() {
47
+ return device_;
48
+ };
49
+
50
+ virtual std::optional<const AVCodec*> find_codec(
51
+ [[maybe_unused]] const AVCodecID& codec_id,
52
+ [[maybe_unused]] bool is_decoder = true) {
53
+ return std::nullopt;
54
+ };
55
+
56
+ // Initialize the device with the codec context, which is needed for the
57
+ // default sendPacket/receiveFrame/flush implementations.
58
+ virtual void initialize(const SharedAVCodecContext& codec_context) = 0;
59
+
60
+ // Initialize state needed to decode packets into raw AVFrames.
61
+ virtual void initialize_video_decoding(
62
+ [[maybe_unused]] const CodecParameters& codec_parameters,
63
+ [[maybe_unused]] const VideoStreamOptions& video_stream_options) {}
64
+
65
+ // Same, from a demuxed stream: this is what SingleStreamDecoder calls, while
66
+ // PacketDecoder calls the overload above. Interfaces only need to implement
67
+ // the overload above. This one stays virtual so that out-of-tree interfaces
68
+ // overriding it keep working with SingleStreamDecoder.
69
+ virtual void initialize_video_decoding(
70
+ const AVStream* av_stream,
71
+ const UniqueDecodingAVFormatContext& av_format_ctx,
72
+ const VideoStreamOptions& video_stream_options) {
73
+ STD_TORCH_CHECK(av_stream != nullptr, "avStream is null");
74
+ initialize_video_decoding(
75
+ CodecParameters(*av_stream, av_format_ctx->iformat),
76
+ video_stream_options);
77
+ }
78
+
79
+ // Initialize state needed to color-convert decoded AVFrames into output
80
+ // tensors.
81
+ virtual void initialize_color_conversion(
82
+ [[maybe_unused]] const VideoStreamOptions& video_stream_options,
83
+ [[maybe_unused]] const std::vector<std::unique_ptr<Transform>>&
84
+ transforms = {},
85
+ [[maybe_unused]] const std::optional<FrameDims>& resized_output_dims =
86
+ std::nullopt) {}
87
+
88
+ // Convenience for the combined decode + color-convert path, kept for BC as
89
+ // it's used by SingleStreamDecoder and out-of-tree interfaces rely on it.
90
+ void initialize_video(
91
+ const AVStream* av_stream,
92
+ const UniqueDecodingAVFormatContext& av_format_ctx,
93
+ const VideoStreamOptions& video_stream_options,
94
+ const std::vector<std::unique_ptr<Transform>>& transforms,
95
+ const std::optional<FrameDims>& resized_output_dims) {
96
+ initialize_video_decoding(av_stream, av_format_ctx, video_stream_options);
97
+ initialize_color_conversion(
98
+ video_stream_options, transforms, resized_output_dims);
99
+ }
100
+
101
+ // Initialize the device with parameters specific to audio decoding. There is
102
+ // a default empty implementation.
103
+ virtual void initialize_audio(
104
+ [[maybe_unused]] const AudioStreamOptions& audio_stream_options,
105
+ [[maybe_unused]] double stream_start_seconds = 0.0) {}
106
+
107
+ // Flush any remaining samples from the audio resampler buffer.
108
+ // When sample rate conversion is involved, some samples may be buffered
109
+ // between frames for proper interpolation. This function flushes those
110
+ // buffered samples.
111
+ // Returns an optional tensor containing the flushed samples, or std::nullopt
112
+ // if there are no buffered samples or audio is not supported.
113
+ virtual std::optional<torch::stable::Tensor> maybe_flush_audio_buffers() {
114
+ return std::nullopt;
115
+ }
116
+
117
+ // In order for decoding to actually happen on an FFmpeg managed hardware
118
+ // device, we need to register the DeviceInterface managed
119
+ // AVHardwareDeviceContext with the AVCodecContext. We don't need to do this
120
+ // on the CPU and if FFmpeg is not managing the hardware device.
121
+ virtual void register_hardware_device_with_codec(
122
+ [[maybe_unused]] AVCodecContext* codec_context) {}
123
+
124
+ // The dtype that should be used for the pre-allocated tensors on batch APIs.
125
+ // Usually that will just be the user's requested dtype, but not always: on
126
+ // CUDA with SDR videos when float32 is asked, will fallback from P016 to NV12
127
+ // to avoid falling back all the way to the CPU. The pre-allocated tensors
128
+ // then need to be uint8, not float32.
129
+ virtual OutputDtype get_pre_allocation_dtype(
130
+ OutputDtype requested_dtype) const {
131
+ return requested_dtype;
132
+ }
133
+
134
+ virtual void convert_av_frame_to_frame_output(
135
+ const AVFrame& av_frame,
136
+ FrameOutput& frame_output,
137
+ std::optional<torch::stable::Tensor> pre_allocated_output_tensor =
138
+ std::nullopt) = 0;
139
+
140
+ // ------------------------------------------
141
+ // Extension points for custom decoding paths
142
+ // ------------------------------------------
143
+
144
+ // Returns AVSUCCESS on success, AVERROR(EAGAIN) if decoder queue full, or
145
+ // other AVERROR on failure
146
+ // Default implementation uses FFmpeg directly
147
+ // The packet is borrowed: an implementation that hands it to something which
148
+ // takes ownership (a bitstream filter, say) must reference it first.
149
+ virtual int send_packet(const AVPacket& av_packet) {
150
+ STD_TORCH_CHECK(
151
+ codec_context_ != nullptr,
152
+ "Codec context not available for default packet sending");
153
+ return avcodec_send_packet(codec_context_.get(), &av_packet);
154
+ }
155
+
156
+ // Send an EOF packet to flush the decoder
157
+ // Returns AVSUCCESS on success, or other AVERROR on failure
158
+ // Default implementation uses FFmpeg directly
159
+ virtual int send_eof_packet() {
160
+ STD_TORCH_CHECK(
161
+ codec_context_ != nullptr,
162
+ "Codec context not available for default EOF packet sending");
163
+ return avcodec_send_packet(codec_context_.get(), nullptr);
164
+ }
165
+
166
+ // Returns AVSUCCESS on success, AVERROR(EAGAIN) if no frame ready,
167
+ // AVERROR_EOF if end of stream, or other AVERROR on failure
168
+ // Default implementation uses FFmpeg directly
169
+ virtual int receive_frame(UniqueAVFrame& av_frame) {
170
+ STD_TORCH_CHECK(
171
+ codec_context_ != nullptr,
172
+ "Codec context not available for default frame receiving");
173
+ return avcodec_receive_frame(codec_context_.get(), av_frame.get());
174
+ }
175
+
176
+ virtual void make_frame_standalone([[maybe_unused]] UniqueAVFrame& av_frame) {
177
+ };
178
+
179
+ virtual std::optional<torch::stable::Tensor> get_frame_storage(
180
+ [[maybe_unused]] const AVFrame& av_frame) const {
181
+ return std::nullopt;
182
+ }
183
+
184
+ // Flush remaining frames from decoder
185
+ virtual void flush() {
186
+ STD_TORCH_CHECK(
187
+ codec_context_ != nullptr,
188
+ "Codec context not available for default flushing");
189
+ avcodec_flush_buffers(codec_context_.get());
190
+
191
+ // We also manually flush any remaining frames in the decoder buffer. We
192
+ // shouldn't have to do this, because avcodec_flush_buffers should handle
193
+ // it, but some codecs like HEVC may still have frames buffered internally
194
+ // in edge cases (ex. hitting EOF) as observed in
195
+ // https://github.com/meta-pytorch/torchcodec/issues/1339.
196
+ UniqueAVFrame tmp(av_frame_alloc());
197
+ while (avcodec_receive_frame(codec_context_.get(), tmp.get()) ==
198
+ AVSUCCESS) {
199
+ }
200
+ }
201
+
202
+ virtual std::string get_details() {
203
+ return "";
204
+ }
205
+
206
+ virtual UniqueAVFrame convert_tensor_to_av_frame_for_encoding(
207
+ [[maybe_unused]] const torch::stable::Tensor& tensor,
208
+ [[maybe_unused]] int frame_index,
209
+ [[maybe_unused]] AVCodecContext* codec_context) {
210
+ STD_TORCH_CHECK(false, "convertTensorToAVFrameForEncoding not implemented");
211
+ }
212
+
213
+ // Returns the pixel format the encoder should use for this device.
214
+ virtual AVPixelFormat get_encoding_pixel_format(
215
+ [[maybe_unused]] const AVCodec& av_codec,
216
+ [[maybe_unused]] const std::optional<std::string>& user_pixel_format)
217
+ const {
218
+ STD_TORCH_CHECK(false, "get_encoding_pixel_format not implemented");
219
+ }
220
+
221
+ // No-op on CPU so the encoder can call it unconditionally; HW devices
222
+ // override to attach an AVHWFramesContext.
223
+ virtual void setup_hardware_frame_context_for_encoding(
224
+ [[maybe_unused]] AVCodecContext* codec_context) {}
225
+
226
+ virtual std::optional<const AVCodec*> find_hardware_encoder(
227
+ [[maybe_unused]] const AVCodecID& codec_id) {
228
+ STD_TORCH_CHECK(false, "findHardwareEncoder not implemented");
229
+ }
230
+
231
+ protected:
232
+ StableDevice device_;
233
+ SharedAVCodecContext codec_context_;
234
+ AVMediaType av_media_type_;
235
+ };
236
+
237
+ using CreateDeviceInterfaceFn =
238
+ std::function<DeviceInterface*(const StableDevice& device)>;
239
+
240
+ TORCHCODEC_THIRD_PARTY_API bool register_device_interface(
241
+ const DeviceInterfaceKey& key,
242
+ const CreateDeviceInterfaceFn create_interface);
243
+
244
+ FORCE_PUBLIC_VISIBILITY void validate_device_interface(
245
+ const std::string& device,
246
+ const std::string& variant = "default");
247
+
248
+ TORCHCODEC_THIRD_PARTY_API std::unique_ptr<DeviceInterface>
249
+ create_device_interface(
250
+ const StableDevice& device,
251
+ const std::string_view variant = "default");
252
+
253
+ torch::stable::Tensor rgb_av_frame_to_tensor(const AVFrame& av_frame);
254
+
255
+ } // namespace facebook::torchcodec