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,424 @@
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 <cstdint>
10
+ #include <memory>
11
+ #include <ostream>
12
+ #include <string_view>
13
+
14
+ #include "AVIOContextHolder.h"
15
+ #include "DeviceInterface.h"
16
+ #include "FFMPEGCommon.h"
17
+ #include "Frame.h"
18
+ #include "Metadata.h"
19
+ #include "StableABICompat.h"
20
+ #include "StreamOptions.h"
21
+ #include "Transform.h"
22
+
23
+ namespace facebook::torchcodec {
24
+
25
+ // The SingleStreamDecoder class can be used to decode video frames to Tensors.
26
+ // Note that SingleStreamDecoder is not thread-safe.
27
+ // Do not call non-const APIs concurrently on the same object.
28
+ class FORCE_PUBLIC_VISIBILITY SingleStreamDecoder {
29
+ public:
30
+ // --------------------------------------------------------------------------
31
+ // CONSTRUCTION API
32
+ // --------------------------------------------------------------------------
33
+
34
+ // Creates a SingleStreamDecoder from the video at videoFilePath.
35
+ explicit SingleStreamDecoder(
36
+ const std::string& video_file_path,
37
+ SeekMode seek_mode = SeekMode::exact);
38
+
39
+ // Creates a SingleStreamDecoder using the provided AVIOContext inside the
40
+ // AVIOContextHolder. The AVIOContextHolder wraps an IOInterface that
41
+ // specializes how the custom read, seek and writes work (in-memory tensor,
42
+ // Python file-like, ...).
43
+ explicit SingleStreamDecoder(
44
+ std::unique_ptr<AVIOContextHolder> context,
45
+ SeekMode seek_mode = SeekMode::exact);
46
+
47
+ // --------------------------------------------------------------------------
48
+ // VIDEO METADATA QUERY API
49
+ // --------------------------------------------------------------------------
50
+
51
+ // Updates the metadata of the video to accurate values obtained by scanning
52
+ // the contents of the video file. Also updates each StreamInfo's index, i.e.
53
+ // the allFrames and keyFrames vectors.
54
+ void scan_file_and_update_metadata_and_index();
55
+
56
+ // Sorts the keyFrames and allFrames vectors in each StreamInfo by pts.
57
+ void sort_all_frames();
58
+
59
+ // Returns the metadata for the container.
60
+ ContainerMetadata get_container_metadata() const;
61
+
62
+ // Returns the seek mode of this decoder.
63
+ SeekMode get_seek_mode() const;
64
+
65
+ // Returns the active stream index. Returns -2 if no stream is active.
66
+ int get_active_stream_index() const;
67
+
68
+ // Returns the key frame indices as a tensor. The tensor is 1D and contains
69
+ // int64 values, where each value is the frame index for a key frame.
70
+ torch::stable::Tensor get_key_frame_indices();
71
+
72
+ // FrameMappings is used for the custom_frame_mappings seek mode to store
73
+ // metadata of frames in a stream. The size of all tensors in this struct must
74
+ // match.
75
+
76
+ // --------------------------------------------------------------------------
77
+ // ADDING STREAMS API
78
+ // --------------------------------------------------------------------------
79
+ struct FrameMappings {
80
+ // 1D tensor of int64, each value is the PTS of a frame in timebase units.
81
+ torch::stable::Tensor all_frames;
82
+ // 1D tensor of bool, each value indicates if the corresponding frame in
83
+ // all_frames is a key frame.
84
+ torch::stable::Tensor is_key_frame;
85
+ // 1D tensor of int64, each value is the duration of the corresponding frame
86
+ // in all_frames in timebase units.
87
+ torch::stable::Tensor duration;
88
+ };
89
+
90
+ void add_video_stream(
91
+ int stream_index,
92
+ std::vector<Transform*>& transforms,
93
+ const VideoStreamOptions& video_stream_options = VideoStreamOptions(),
94
+ std::optional<FrameMappings> custom_frame_mappings = std::nullopt);
95
+ void add_audio_stream(
96
+ int stream_index,
97
+ const AudioStreamOptions& audio_stream_options = AudioStreamOptions());
98
+
99
+ // --------------------------------------------------------------------------
100
+ // DECODING AND SEEKING APIs
101
+ // --------------------------------------------------------------------------
102
+
103
+ // Places the cursor at the first frame on or after the position in seconds.
104
+ // Calling getNextFrame() will return the first frame at
105
+ // or after this position.
106
+ void set_cursor_pts_in_seconds(double seconds);
107
+
108
+ // Decodes the frame where the current cursor position is. It also advances
109
+ // the cursor to the next frame.
110
+ FrameOutput get_next_frame();
111
+
112
+ FrameOutput get_frame_at_index(int64_t frame_index);
113
+
114
+ // Returns frames at the given indices for a given stream as a single stacked
115
+ // Tensor.
116
+ FrameBatchOutput get_frames_at_indices(
117
+ const torch::stable::Tensor& frame_indices);
118
+
119
+ // Returns frames within a given range. The range is defined by [start, stop).
120
+ // The values retrieved from the range are: [start, start+step,
121
+ // start+(2*step), start+(3*step), ..., stop). The default for step is 1.
122
+ FrameBatchOutput
123
+ get_frames_in_range(int64_t start, int64_t stop, int64_t step);
124
+
125
+ // Decodes the first frame in any added stream that is visible at a given
126
+ // timestamp. Frames in the video have a presentation timestamp and a
127
+ // duration. For example, if a frame has presentation timestamp of 5.0s and a
128
+ // duration of 1.0s, it will be visible in the timestamp range [5.0, 6.0).
129
+ // i.e. it will be returned when this function is called with seconds=5.0 or
130
+ // seconds=5.999, etc.
131
+ FrameOutput get_frame_played_at(double seconds);
132
+
133
+ FrameBatchOutput get_frames_played_at(
134
+ const torch::stable::Tensor& timestamps);
135
+
136
+ // Returns frames within a given pts range. The range is defined by
137
+ // [startSeconds, stopSeconds) with respect to the pts values for frames. The
138
+ // returned frames are in pts order.
139
+ //
140
+ // Note that while stopSeconds is excluded in the half open range, this really
141
+ // only makes a difference when stopSeconds is exactly the pts value for a
142
+ // frame. Otherwise, the moment in time immediately before stopSeconds is in
143
+ // the range, and that time maps to the same frame as stopSeconds.
144
+ //
145
+ // The frames returned are the frames that would be played by our abstract
146
+ // player. Our abstract player displays frames based on pts only. It displays
147
+ // frame i starting at the pts for frame i, and stops at the pts for frame
148
+ // i+1. This model ignores a frame's reported duration.
149
+ //
150
+ // Valid values for startSeconds and stopSeconds are:
151
+ //
152
+ // [beginStreamPtsSecondsFromContent, endStreamPtsSecondsFromContent)
153
+ //
154
+ // If fps is specified, frames are resampled to match the target frame
155
+ // rate by duplicating or dropping frames as necessary.
156
+ FrameBatchOutput get_frames_played_in_range(
157
+ double start_seconds,
158
+ double stop_seconds,
159
+ std::optional<double> fps = std::nullopt);
160
+
161
+ AudioFramesOutput get_frames_played_in_range_audio(
162
+ double start_seconds,
163
+ std::optional<double> stop_seconds_optional = std::nullopt);
164
+
165
+ class EndOfFileException : public std::runtime_error {
166
+ public:
167
+ explicit EndOfFileException(const std::string& msg)
168
+ : std::runtime_error(msg) {}
169
+ };
170
+
171
+ // --------------------------------------------------------------------------
172
+ // MORALLY PRIVATE APIS
173
+ // --------------------------------------------------------------------------
174
+ // These are APIs that should be private, but that are effectively exposed for
175
+ // practical reasons, typically for testing purposes.
176
+
177
+ // Once getFrameAtIndex supports the preAllocatedOutputTensor parameter, we
178
+ // can move it back to private.
179
+ FrameOutput get_frame_at_index_internal(
180
+ int64_t frame_index,
181
+ std::optional<torch::stable::Tensor> pre_allocated_output_tensor =
182
+ std::nullopt);
183
+
184
+ // Exposed for _test_frame_pts_equality, which is used to test non-regression
185
+ // of pts resolution (64 to 32 bit floats)
186
+ double get_pts_seconds_for_frame(int64_t frame_index);
187
+
188
+ // Exposed for performance testing.
189
+ struct DecodeStats {
190
+ int64_t num_seeks_attempted = 0;
191
+ int64_t num_seeks_done = 0;
192
+ int64_t num_seeks_skipped = 0;
193
+ int64_t num_packets_read = 0;
194
+ int64_t num_packets_sent_to_decoder = 0;
195
+ int64_t num_frames_received_by_decoder = 0;
196
+ int64_t num_flushes = 0;
197
+ };
198
+
199
+ DecodeStats get_decode_stats() const;
200
+ void reset_decode_stats();
201
+
202
+ std::string get_device_interface_details() const;
203
+
204
+ private:
205
+ // --------------------------------------------------------------------------
206
+ // STREAMINFO AND ASSOCIATED STRUCTS
207
+ // --------------------------------------------------------------------------
208
+
209
+ struct FrameInfo {
210
+ int64_t pts = 0;
211
+
212
+ // The value of the nextPts default is important: the last frame's nextPts
213
+ // will be INT64_MAX, which ensures that the allFrames vec contains
214
+ // FrameInfo structs with *increasing* nextPts values. That's a necessary
215
+ // condition for the binary searches on those values to work properly (as
216
+ // typically done during pts -> index conversions).
217
+ // TODO: This field is unset (left to the default) for entries in the
218
+ // keyFrames vec!
219
+ int64_t next_pts = INT64_MAX;
220
+
221
+ // Note that frameIndex is ALWAYS the index into all of the frames in that
222
+ // stream, even when the FrameInfo is part of the key frame index. Given a
223
+ // FrameInfo for a key frame, the frameIndex allows us to know which frame
224
+ // that is in the stream.
225
+ int64_t frame_index = 0;
226
+
227
+ // Indicates whether a frame is a key frame. It may appear redundant as it's
228
+ // only true for FrameInfos in the keyFrames index, but it is needed to
229
+ // correctly map frames between allFrames and keyFrames during the scan.
230
+ bool is_key_frame = false;
231
+ };
232
+
233
+ struct StreamInfo {
234
+ int stream_index = -1;
235
+ AVStream* stream = nullptr;
236
+ AVMediaType av_media_type = AVMEDIA_TYPE_UNKNOWN;
237
+
238
+ AVRational time_base = {};
239
+ SharedAVCodecContext codec_context;
240
+
241
+ // The FrameInfo indices we built when scanFileAndUpdateMetadataAndIndex was
242
+ // called.
243
+ std::vector<FrameInfo> key_frames;
244
+ std::vector<FrameInfo> all_frames;
245
+
246
+ VideoStreamOptions video_stream_options;
247
+ AudioStreamOptions audio_stream_options;
248
+ };
249
+
250
+ // --------------------------------------------------------------------------
251
+ // INITIALIZERS
252
+ // --------------------------------------------------------------------------
253
+
254
+ void initialize_decoder();
255
+
256
+ // Reads the user provided frame index and updates each StreamInfo's index,
257
+ // i.e. the allFrames and keyFrames vectors, and
258
+ // endStreamPtsSecondsFromContent
259
+ void read_custom_frame_mappings_update_metadata_and_index(
260
+ int stream_index,
261
+ FrameMappings custom_frame_mappings);
262
+ // --------------------------------------------------------------------------
263
+ // DECODING APIS AND RELATED UTILS
264
+ // --------------------------------------------------------------------------
265
+
266
+ void set_cursor(int64_t pts);
267
+ void set_cursor(double) = delete; // prevent calls with doubles and floats
268
+ int64_t last_decoded_av_frame_end_pts() const;
269
+ bool can_we_avoid_seeking() const;
270
+
271
+ bool maybe_seek_to_before_desired_pts();
272
+
273
+ UniqueAVFrame decode_av_frame(
274
+ std::function<bool(const AVFrame&)> filter_function);
275
+
276
+ FrameOutput get_next_frame_internal(
277
+ std::optional<torch::stable::Tensor> pre_allocated_output_tensor =
278
+ std::nullopt);
279
+
280
+ // Permutes HWC to CHW if needed, then converts to float32 and normalizes to
281
+ // [0, 1] if the active stream's outputDtype is FLOAT32.
282
+ torch::stable::Tensor maybe_permute_and_convert_dtype(
283
+ torch::stable::Tensor& tensor);
284
+
285
+ FrameOutput convert_av_frame_to_frame_output(
286
+ const AVFrame& av_frame,
287
+ std::optional<torch::stable::Tensor> pre_allocated_output_tensor =
288
+ std::nullopt);
289
+
290
+ // --------------------------------------------------------------------------
291
+ // PTS <-> INDEX CONVERSIONS
292
+ // --------------------------------------------------------------------------
293
+
294
+ int get_key_frame_identifier(int64_t pts) const;
295
+
296
+ // Returns the key frame index of the presentation timestamp using our index.
297
+ // We build this index by scanning the file in
298
+ // scanFileAndUpdateMetadataAndIndex
299
+ int get_key_frame_index_for_pts_using_scanned_index(
300
+ const std::vector<SingleStreamDecoder::FrameInfo>& key_frames,
301
+ int64_t pts) const;
302
+
303
+ int64_t seconds_to_index_lower_bound(double seconds) const;
304
+
305
+ int64_t seconds_to_index_upper_bound(double seconds);
306
+
307
+ int64_t get_pts(int64_t frame_index);
308
+
309
+ // Returns the output frame dimensions for video frames.
310
+ // If resizedOutputDims_ is set (via resize, crop, or rotation transforms),
311
+ // returns that. Otherwise, returns preRotationDims_.
312
+ //
313
+ // Note: if resizedOutputDims_ is null, there is no rotation (the
314
+ // rotation transform would have set it), so preRotationDims_ ==
315
+ // postRotationDims_. This makes it safe to use preRotationDims_ as the
316
+ // fallback.
317
+ FrameDims get_output_dims() const;
318
+
319
+ // --------------------------------------------------------------------------
320
+ // STREAM AND METADATA APIS
321
+ // --------------------------------------------------------------------------
322
+
323
+ void add_stream(
324
+ int stream_index,
325
+ AVMediaType media_type,
326
+ const StableDevice& device = StableDevice(kStableCPU),
327
+ const std::string_view device_variant = "default",
328
+ std::optional<int> ffmpeg_thread_count = std::nullopt);
329
+
330
+ // Returns the "best" stream index for a given media type. The "best" is
331
+ // determined by various heuristics in FFMPEG.
332
+ // See
333
+ // https://ffmpeg.org/doxygen/trunk/group__lavf__decoding.html#ga757780d38f482deb4d809c6c521fbcc2
334
+ // for more details about the heuristics.
335
+ // Returns the key frame index of the presentation timestamp using FFMPEG's
336
+ // index. Note that this index may be truncated for some files.
337
+
338
+ // --------------------------------------------------------------------------
339
+ // VALIDATION UTILS
340
+ // --------------------------------------------------------------------------
341
+
342
+ void validate_active_stream(
343
+ std::optional<AVMediaType> av_media_type = std::nullopt);
344
+ void validate_scanned_all_streams(const std::string& msg);
345
+ void validate_frame_index(
346
+ const StreamMetadata& stream_metadata,
347
+ int64_t frame_index);
348
+
349
+ // --------------------------------------------------------------------------
350
+ // ATTRIBUTES
351
+ // --------------------------------------------------------------------------
352
+
353
+ SeekMode seek_mode_;
354
+ ContainerMetadata container_metadata_;
355
+ UniqueDecodingAVFormatContext format_context_;
356
+ std::unique_ptr<DeviceInterface> device_interface_;
357
+ std::map<int, StreamInfo> stream_infos_;
358
+ const int no_active_stream_ = -2;
359
+ int active_stream_index_ = no_active_stream_;
360
+
361
+ // The desired position of the cursor in the stream. We send frames >= this
362
+ // pts to the user when they request a frame.
363
+ int64_t cursor_ = INT64_MIN;
364
+ bool cursor_was_just_set_ = false;
365
+ // Whether the container is an MPEG program stream, whose demuxer needs
366
+ // special care after a seek. See decode_av_frame().
367
+ bool is_mpeg_ps_ = false;
368
+ // Initialized to INT64_MIN instead of 0. With 0, canWeAvoidSeeking() could
369
+ // incorrectly skip a seek when the internal FFmpeg frame index (used by
370
+ // av_index_search_timestamp() in approximate mode) had not yet been built,
371
+ // as some formats (mkv, webm) delay building it until the first seek.
372
+ // With INT64_MIN, we always seek when retrieving the first frame. This
373
+ // means we correctly seek when the first requested frame is far into the
374
+ // video, at the cost of an unnecessary (likely cheap) seek when the first
375
+ // requested frame is near the start.
376
+ // See: https://github.com/meta-pytorch/torchcodec/pull/1259
377
+ int64_t last_decoded_av_frame_pts_ = INT64_MIN;
378
+ int64_t last_decoded_av_frame_duration_ = 0;
379
+ AudioPtsExtrapolator audio_pts_extrapolator_;
380
+
381
+ // Stores various internal decoding stats.
382
+ DecodeStats decode_stats_;
383
+
384
+ // Stores the AVIOContext for the input buffer.
385
+ std::unique_ptr<AVIOContextHolder> avio_context_holder_;
386
+
387
+ // We will receive a vector of transforms upon adding a stream and store it
388
+ // here. However, we need to know if any of those operations change the
389
+ // dimensions of the output frame. If they do, we need to figure out what are
390
+ // the final dimensions of the output frame after ALL transformations. We
391
+ // figure this out as soon as we receive the transforms. If any of the
392
+ // transforms change the final output frame dimensions, we store that in
393
+ // resizedOutputDims_. If resizedOutputDims_ has no value, that means there
394
+ // are no transforms that change the output frame dimensions.
395
+ //
396
+ // The priority order for output frame dimensions is:
397
+ //
398
+ // 1. resizedOutputDims_; the resize requested by the user (or rotation)
399
+ // always takes priority.
400
+ // 2. The dimensions of the actual decoded AVFrame. This can change
401
+ // per-decoded frame, and is unknown in SingleStreamDecoder. Only the
402
+ // DeviceInterface learns it immediately after decoding a raw frame but
403
+ // before the color conversion.
404
+ // 3. preRotationDims_; the raw encoded dimensions from FFmpeg metadata
405
+ // (before any rotation is applied). Used as fallback for tensor
406
+ // allocation when resizedOutputDims_ is not set, which only happens
407
+ // when no rotation is needed, so preRotationDims_ is the correct value.
408
+ std::vector<std::unique_ptr<Transform>> transforms_;
409
+ std::optional<FrameDims> resized_output_dims_;
410
+ FrameDims pre_rotation_dims_;
411
+
412
+ // Whether or not we have already scanned all streams to update the metadata.
413
+ bool scanned_all_streams_ = false;
414
+
415
+ // Tracks that we've already been initialized.
416
+ bool initialized_ = false;
417
+ };
418
+
419
+ // Prints the SingleStreamDecoder::DecodeStats to the ostream.
420
+ std::ostream& operator<<(
421
+ std::ostream& os,
422
+ const SingleStreamDecoder::DecodeStats& stats);
423
+
424
+ } // namespace facebook::torchcodec
@@ -0,0 +1,213 @@
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 <torch/csrc/stable/accelerator.h>
10
+ #include <torch/csrc/stable/device.h>
11
+ #include <torch/csrc/stable/library.h>
12
+ #include <torch/csrc/stable/ops.h>
13
+ #include <torch/csrc/stable/tensor.h>
14
+ #include <torch/headeronly/core/DeviceType.h>
15
+ #include <torch/headeronly/core/ScalarType.h>
16
+
17
+ #include <torch/headeronly/core/TensorAccessor.h>
18
+
19
+ #include <sstream>
20
+ #include <stdexcept>
21
+ #include <string>
22
+ #include <vector>
23
+
24
+ // Symbol visibility for the shared library
25
+ #ifdef _WIN32
26
+ #define FORCE_PUBLIC_VISIBILITY __declspec(dllexport)
27
+ #else
28
+ #define FORCE_PUBLIC_VISIBILITY __attribute__((visibility("default")))
29
+ #endif
30
+
31
+ // Flag meant to be used for any API that third-party libraries may call.
32
+ // It ensures the API symbol is always public.
33
+ #ifdef _WIN32
34
+ #define TORCHCODEC_THIRD_PARTY_API
35
+ #else
36
+ #define TORCHCODEC_THIRD_PARTY_API __attribute__((visibility("default")))
37
+ #endif
38
+
39
+ // Index error check - throws std::out_of_range which pybind11 maps to
40
+ // IndexError Use this for index validation errors that should raise IndexError
41
+ // in Python
42
+ #define STABLE_CHECK_INDEX(cond, msg) \
43
+ do { \
44
+ if (!(cond)) { \
45
+ throw std::out_of_range(std::string(msg)); \
46
+ } \
47
+ } while (false)
48
+
49
+ namespace facebook::torchcodec {
50
+
51
+ // Device types
52
+ using StableDevice = torch::stable::Device;
53
+ using StableDeviceType = torch::headeronly::DeviceType;
54
+
55
+ // DeviceGuard for CUDA context management
56
+ using StableDeviceGuard = torch::stable::accelerator::DeviceGuard;
57
+
58
+ // Device type constants
59
+ constexpr auto kStableCPU = torch::headeronly::DeviceType::CPU;
60
+ constexpr auto kStableCUDA = torch::headeronly::DeviceType::CUDA;
61
+ constexpr auto kStableXPU = torch::headeronly::DeviceType::XPU;
62
+
63
+ // Scalar type constants
64
+ constexpr auto kStableUInt8 = torch::headeronly::ScalarType::Byte;
65
+ constexpr auto kStableUInt16 = torch::headeronly::ScalarType::UInt16;
66
+ constexpr auto kStableInt16 = torch::headeronly::ScalarType::Short;
67
+ constexpr auto kStableInt32 = torch::headeronly::ScalarType::Int;
68
+ constexpr auto kStableInt64 = torch::headeronly::ScalarType::Long;
69
+ constexpr auto kStableFloat32 = torch::headeronly::ScalarType::Float;
70
+ constexpr auto kStableFloat64 = torch::headeronly::ScalarType::Double;
71
+ constexpr auto kStableBool = torch::headeronly::ScalarType::Bool;
72
+
73
+ // Note: the magic use of torch_call_dispatcher is what is officially
74
+ // recommended
75
+ // https://github.com/pytorch/pytorch/blob/89f3759429b96a8693b698f013990240bb4e25b3/docs/source/notes/libtorch_stable_abi.md?plain=1#L221
76
+ // It allows us to make an ABI-stable call to an op that isn't officially in the
77
+ // stable ABI. Some of these ops currently include permute, rot90, etc.
78
+ // See also how xformers relies on it:
79
+ // https://github.com/facebookresearch/xformers/blob/720adff2b021f6f43957718514f5be3d10e36fb1/xformers/csrc/pt_stable_utils.h#L85
80
+
81
+ // TODO_STABLE_ABI: upstream?
82
+ inline torch::stable::Tensor stable_permute(
83
+ const torch::stable::Tensor& self,
84
+ std::vector<int64_t> dims) {
85
+ const auto num_args = 2;
86
+ std::array<StableIValue, num_args> stack{
87
+ torch::stable::detail::from(self), torch::stable::detail::from(dims)};
88
+ TORCH_ERROR_CODE_CHECK(torch_call_dispatcher(
89
+ "aten::permute", "", stack.data(), TORCH_ABI_VERSION));
90
+ return torch::stable::detail::to<torch::stable::Tensor>(stack[0]);
91
+ }
92
+
93
+ // TODO_STABLE_ABI: upstream?
94
+ inline torch::stable::Tensor stable_cat(
95
+ const std::vector<torch::stable::Tensor>& tensors,
96
+ int64_t dim) {
97
+ const auto num_args = 2;
98
+ std::array<StableIValue, num_args> stack{
99
+ torch::stable::detail::from(tensors), torch::stable::detail::from(dim)};
100
+ TORCH_ERROR_CODE_CHECK(
101
+ torch_call_dispatcher("aten::cat", "", stack.data(), TORCH_ABI_VERSION));
102
+ return torch::stable::detail::to<torch::stable::Tensor>(stack[0]);
103
+ }
104
+
105
+ // TODO_STABLE_ABI: upstream?
106
+ inline torch::stable::Tensor stable_flip(
107
+ const torch::stable::Tensor& self,
108
+ std::vector<int64_t> dims) {
109
+ const auto num_args = 2;
110
+ std::array<StableIValue, num_args> stack{
111
+ torch::stable::detail::from(self), torch::stable::detail::from(dims)};
112
+ TORCH_ERROR_CODE_CHECK(
113
+ torch_call_dispatcher("aten::flip", "", stack.data(), TORCH_ABI_VERSION));
114
+ return torch::stable::detail::to<torch::stable::Tensor>(stack[0]);
115
+ }
116
+
117
+ // TODO_STABLE_ABI: upstream?
118
+ inline torch::stable::Tensor stable_rot90(
119
+ const torch::stable::Tensor& self,
120
+ int k,
121
+ int64_t dim0,
122
+ int64_t dim1) {
123
+ const auto num_args = 3;
124
+ std::array<StableIValue, num_args> stack{
125
+ torch::stable::detail::from(self),
126
+ torch::stable::detail::from(static_cast<int64_t>(k)),
127
+ torch::stable::detail::from(std::vector<int64_t>{dim0, dim1})};
128
+ TORCH_ERROR_CODE_CHECK(torch_call_dispatcher(
129
+ "aten::rot90", "", stack.data(), TORCH_ABI_VERSION));
130
+ return torch::stable::detail::to<torch::stable::Tensor>(stack[0]);
131
+ }
132
+
133
+ // TODO_STABLE_ABI: upstream?
134
+ inline torch::stable::Tensor stable_div(
135
+ const torch::stable::Tensor& self,
136
+ double other) {
137
+ auto divisor = torch::stable::full({}, other);
138
+ const auto num_args = 2;
139
+ std::array<StableIValue, num_args> stack{
140
+ torch::stable::detail::from(self), torch::stable::detail::from(divisor)};
141
+ TORCH_ERROR_CODE_CHECK(torch_call_dispatcher(
142
+ "aten::div", "Tensor", stack.data(), TORCH_ABI_VERSION));
143
+ return torch::stable::detail::to<torch::stable::Tensor>(stack[0]);
144
+ }
145
+
146
+ // Shorthand for torch::stable::select(tensor, 0, index), i.e. tensor[index].
147
+ inline torch::stable::Tensor select_row(
148
+ const torch::stable::Tensor& tensor,
149
+ int64_t index) {
150
+ return torch::stable::select(tensor, 0, index);
151
+ }
152
+
153
+ template <typename T, size_t N>
154
+ torch::headeronly::HeaderOnlyTensorAccessor<T, N> mutable_accessor(
155
+ torch::stable::Tensor& tensor) {
156
+ return torch::headeronly::HeaderOnlyTensorAccessor<T, N>(
157
+ tensor.mutable_data_ptr<T>(),
158
+ tensor.sizes().data(),
159
+ tensor.strides().data());
160
+ }
161
+
162
+ template <typename T, size_t N>
163
+ torch::headeronly::HeaderOnlyTensorAccessor<const T, N> const_accessor(
164
+ const torch::stable::Tensor& tensor) {
165
+ return torch::headeronly::HeaderOnlyTensorAccessor<const T, N>(
166
+ tensor.const_data_ptr<T>(),
167
+ tensor.sizes().data(),
168
+ tensor.strides().data());
169
+ }
170
+
171
+ // Copy row srcIndex from srcTensor into row dstIndex of dstTensor.
172
+ inline void copy_frame(
173
+ torch::stable::Tensor& dst_tensor,
174
+ int64_t dst_index,
175
+ const torch::stable::Tensor& src_tensor,
176
+ int64_t src_index) {
177
+ auto dst = select_row(dst_tensor, dst_index);
178
+ torch::stable::copy_(dst, select_row(src_tensor, src_index));
179
+ }
180
+
181
+ // TODO_STABLE_ABI: this should probably be natively supported by torch::stable.
182
+ // Consider upstreaming.
183
+ inline const char* device_type_name(StableDeviceType device_type) {
184
+ switch (device_type) {
185
+ case kStableCPU:
186
+ return "cpu";
187
+ case kStableCUDA:
188
+ return "cuda";
189
+ case kStableXPU:
190
+ return "xpu";
191
+ default:
192
+ return "unknown";
193
+ }
194
+ }
195
+
196
+ // TODO_STABLE_ABI: This is needed to properly print shape info in error
197
+ // messages. There should probably be a better native way to support it, e.g.
198
+ // torch::headeronly::IntHeaderOnlyArrayRef probably needs to support the `<<`
199
+ // operator. Consider upstreaming.
200
+ inline std::string int_array_ref_to_string(
201
+ torch::headeronly::IntHeaderOnlyArrayRef arr) {
202
+ std::ostringstream ss;
203
+ ss << "[";
204
+ for (size_t i = 0; i < arr.size(); ++i) {
205
+ if (i > 0)
206
+ ss << ", ";
207
+ ss << arr[i];
208
+ }
209
+ ss << "]";
210
+ return ss.str();
211
+ }
212
+
213
+ } // namespace facebook::torchcodec