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,2438 @@
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
+ // fmt headers from torch error out if TORCH_TARGET_VERSION is defined, so we
8
+ // temporarily undefine it.
9
+ // See https://github.com/pytorch/pytorch/pull/174372 for context
10
+ #pragma push_macro("TORCH_TARGET_VERSION")
11
+ #undef TORCH_TARGET_VERSION
12
+ #include <fmt/format.h>
13
+ #pragma pop_macro("TORCH_TARGET_VERSION")
14
+ #include <cstdint>
15
+ #include <cstring>
16
+ #include <limits>
17
+ #include <string>
18
+
19
+ extern "C" {
20
+ #include <libavutil/pixdesc.h>
21
+ }
22
+
23
+ #include "AVIOContextHolder.h"
24
+ #include "AudioConverter.h"
25
+ #include "ColorConverter.h"
26
+ #include "Demuxer.h"
27
+ #include "Encoder.h"
28
+ #include "FileIO.h"
29
+ #include "FileLikeIO.h"
30
+ #include "IOInterface.h"
31
+ #include "Logging.h"
32
+ #include "NVDECCacheConfig.h"
33
+ #include "PacketDecoder.h"
34
+ #include "SingleStreamDecoder.h"
35
+ #include "StableABICompat.h"
36
+ #include "TensorIO.h"
37
+ #include "ValidationUtils.h"
38
+ #include "WavDecoder.h"
39
+
40
+ namespace facebook::torchcodec {
41
+
42
+ // ==============================
43
+ // Define the operators
44
+ // ==============================
45
+ // All instances of accepting the decoder as a tensor must be annotated with
46
+ // `Tensor(a!)`. The `(a!)` part normally indicates that the tensor is being
47
+ // mutated in place. We need it to make sure that torch.compile does not reorder
48
+ // calls to these functions. For more detail, see:
49
+ // https://github.com/pytorch/pytorch/tree/main/aten/src/ATen/native#readme
50
+ //
51
+ STABLE_TORCH_LIBRARY_FRAGMENT(torchcodec_ns, m) {
52
+ m.def("create_from_file(str filename, str? seek_mode=None) -> Tensor");
53
+ m.def(
54
+ "create_from_tensor(Tensor video_tensor, str? seek_mode=None) -> Tensor");
55
+ m.def(
56
+ "_create_from_file_like(int file_like_context, str? seek_mode=None) -> Tensor");
57
+ m.def(
58
+ "_add_video_stream(Tensor(a!) decoder, *, int? num_threads=None, str? dimension_order=None, int? stream_index=None, str device=\"cpu\", str device_variant=\"default\", str transform_specs=\"\", Tensor? custom_frame_mappings_pts=None, Tensor? custom_frame_mappings_duration=None, Tensor? custom_frame_mappings_keyframe_indices=None, str? color_conversion_library=None, str output_dtype=\"uint8\") -> ()");
59
+ m.def(
60
+ "add_video_stream(Tensor(a!) decoder, *, int? num_threads=None, str? dimension_order=None, int? stream_index=None, str device=\"cpu\", str device_variant=\"default\", str transform_specs=\"\", Tensor? custom_frame_mappings_pts=None, Tensor? custom_frame_mappings_duration=None, Tensor? custom_frame_mappings_keyframe_indices=None, str output_dtype=\"uint8\") -> ()");
61
+ m.def(
62
+ "add_audio_stream(Tensor(a!) decoder, *, int? stream_index=None, int? sample_rate=None, int? num_channels=None) -> ()");
63
+ m.def("seek_to_pts(Tensor(a!) decoder, float seconds) -> ()");
64
+ m.def("get_next_frame(Tensor(a!) decoder) -> (Tensor, Tensor, Tensor)");
65
+ m.def(
66
+ "get_frame_at_pts(Tensor(a!) decoder, float seconds) -> (Tensor, Tensor, Tensor)");
67
+ m.def(
68
+ "get_frame_at_index(Tensor(a!) decoder, *, int frame_index) -> (Tensor, Tensor, Tensor)");
69
+ m.def(
70
+ "get_frames_at_indices(Tensor(a!) decoder, *, Tensor frame_indices) -> (Tensor, Tensor, Tensor)");
71
+ m.def(
72
+ "get_frames_in_range(Tensor(a!) decoder, *, int start, int stop, int? step=None) -> (Tensor, Tensor, Tensor)");
73
+ m.def(
74
+ "get_frames_by_pts_in_range(Tensor(a!) decoder, *, float start_seconds, float stop_seconds, float? fps=None) -> (Tensor, Tensor, Tensor)");
75
+ m.def(
76
+ "get_frames_by_pts_in_range_audio(Tensor(a!) decoder, *, float start_seconds, float? stop_seconds) -> (Tensor, Tensor)");
77
+ m.def(
78
+ "get_frames_by_pts(Tensor(a!) decoder, *, Tensor timestamps) -> (Tensor, Tensor, Tensor)");
79
+ m.def("_blocks_create_demuxer_from_file(str filename) -> Tensor");
80
+ m.def("_blocks_create_demuxer_from_tensor(Tensor video_tensor) -> Tensor");
81
+ m.def(
82
+ "_blocks_create_demuxer_from_file_like(int file_like_context) -> Tensor");
83
+ m.def(
84
+ "_blocks_demuxer_add_stream(Tensor(a!) demuxer, int? stream_index=None, str? media_type=None) -> (int, bool)");
85
+ m.def(
86
+ "_blocks_demuxer_get_audio_video_stream_indices(Tensor demuxer) -> Tensor");
87
+ m.def("_blocks_demuxer_container_json_metadata(Tensor demuxer) -> Tensor");
88
+ m.def(
89
+ "_blocks_demuxer_stream_json_metadata(Tensor demuxer, int stream_index) -> Tensor");
90
+ m.def(
91
+ "_blocks_demuxer_next_packet(Tensor(a!) demuxer) -> (Tensor, bool, int)");
92
+ m.def(
93
+ "_blocks_demuxer_seek(Tensor(a!) demuxer, float seconds, int? stream_index=None) -> ()");
94
+ m.def(
95
+ "_blocks_demuxer_scan(Tensor(a!) demuxer, int? stream_index=None) -> (Tensor, Tensor, Tensor, int, int)");
96
+ // The return names are the fields of VideoCodecParameters and
97
+ // AudioCodecParameters, which Python matches them against.
98
+ m.def(
99
+ "_blocks_demuxer_get_codec_parameters(Tensor demuxer, int stream_index) -> (Tensor codec, int[] time_base, Tensor? extradata, int? codec_tag, int? profile, int? level, int? bit_rate, int? bits_per_coded_sample, int? bits_per_raw_sample, Tensor[] coded_side_data_names, Tensor[] coded_side_data_values, int? width, int? height, Tensor? pixel_format, int[]? sample_aspect_ratio, int[]? framerate, int[]? r_frame_rate, Tensor? field_order, Tensor? color_range, Tensor? color_primaries, Tensor? color_transfer_characteristic, Tensor? color_space, Tensor? chroma_location, int? video_delay, Tensor? sample_format, int? sample_rate, Tensor? channel_layout, int? block_align, int? frame_size, int? initial_padding, int? trailing_padding, int? seek_preroll, Tensor? container_format)");
100
+ // Takes the fields of VideoCodecParameters and AudioCodecParameters, under
101
+ // their names.
102
+ m.def(
103
+ "_blocks_create_packet_decoder(str media_type, str codec, int[] time_base, *, Tensor? extradata=None, int? codec_tag=None, int? profile=None, int? level=None, int? bit_rate=None, int? bits_per_coded_sample=None, int? bits_per_raw_sample=None, str[]? coded_side_data_names=None, Tensor[]? coded_side_data_values=None, int? width=None, int? height=None, str? pixel_format=None, int[]? sample_aspect_ratio=None, int[]? framerate=None, int[]? r_frame_rate=None, str? field_order=None, str? color_range=None, str? color_primaries=None, str? color_transfer_characteristic=None, str? color_space=None, str? chroma_location=None, int? video_delay=None, str? sample_format=None, int? sample_rate=None, str? channel_layout=None, int? block_align=None, int? frame_size=None, int? initial_padding=None, int? trailing_padding=None, int? seek_preroll=None, str? container_format=None, int? num_threads=None, str device=\"cpu\") -> Tensor");
104
+ // Takes the arguments of Packet.from_tensor(), under their names.
105
+ m.def(
106
+ "_blocks_create_packet(Tensor data, *, int? pts=None, int? dts=None, int duration=0, int flags=0, str[]? side_data_names=None, Tensor[]? side_data_values=None) -> Tensor");
107
+ // The return names are the Packet properties, which Python matches them
108
+ // against.
109
+ m.def(
110
+ "_blocks_packet_get_fields(Tensor packet) -> (Tensor data, int? pts, int? dts, int duration, int flags, int[] side_data_types, Tensor[] side_data_values)");
111
+ m.def(
112
+ "_blocks_packet_decoder_send_packet(Tensor(a!) decoder, Tensor packet) -> int");
113
+ m.def("_blocks_packet_decoder_send_eof(Tensor(a!) decoder) -> int");
114
+ m.def("_blocks_packet_decoder_reset(Tensor(a!) decoder) -> ()");
115
+ m.def(
116
+ "_blocks_packet_decoder_receive_frame(Tensor(a!) decoder) -> (Tensor, int, int?, float, float, Tensor)");
117
+ m.def(
118
+ "_blocks_audio_packet_decoder_receive_frame(Tensor(a!) decoder) -> (Tensor, int, int?, float, float, int)");
119
+ m.def(
120
+ "_blocks_create_color_converter(str device=\"cpu\", str output_dtype=\"uint8\") -> Tensor");
121
+ m.def(
122
+ "_blocks_create_audio_converter(int? sample_rate=None, int? num_channels=None) -> Tensor");
123
+ m.def(
124
+ "_blocks_audio_converter_convert(Tensor(a!) converter, Tensor samples, int sample_rate) -> Tensor");
125
+ m.def("_blocks_audio_converter_drain(Tensor(a!) converter) -> Tensor");
126
+ m.def("_blocks_audio_converter_reset(Tensor(a!) converter) -> ()");
127
+ m.def(
128
+ "_blocks_convert_frame(Tensor(a!) converter, Tensor frame, Device device) -> Tensor");
129
+ m.def(
130
+ "_blocks_frame_metadata(Tensor frame) -> (int, int, int, int, int, int, int, int, float)");
131
+ m.def("_blocks_get_ffmpeg_enum_name(*, int kind, int value) -> str");
132
+ m.def(
133
+ "_blocks_frame_planes(Tensor frame, Device device) -> (Tensor, Tensor, Tensor, Tensor)");
134
+ m.def("_get_key_frame_indices(Tensor(a!) decoder) -> Tensor");
135
+ m.def("get_json_metadata(Tensor(a!) decoder) -> str");
136
+ m.def("get_container_json_metadata(Tensor(a!) decoder) -> Tensor");
137
+ m.def(
138
+ "get_stream_json_metadata(Tensor(a!) decoder, int stream_index) -> Tensor");
139
+ m.def("_get_json_ffmpeg_library_versions() -> str");
140
+ m.def("_get_backend_details(Tensor(a!) decoder) -> str");
141
+ m.def(
142
+ "_test_frame_pts_equality(Tensor(a!) decoder, *, int frame_index, float pts_seconds_to_test) -> bool");
143
+ m.def("scan_all_streams_to_update_metadata(Tensor(a!) decoder) -> ()");
144
+ m.def("create_streaming_encoder() -> Tensor");
145
+ m.def("streaming_encoder_close(Tensor(a!) encoder) -> ()");
146
+ m.def(
147
+ "streaming_encoder_add_video_stream(Tensor(a!) encoder, int height, int width, float frame_rate, str device=\"cpu\", str? codec=None, str? pixel_format=None, float? crf=None, str? preset=None, str[]? extra_options=None) -> int");
148
+ m.def(
149
+ "streaming_encoder_add_audio_stream(Tensor(a!) encoder, int sample_rate, int num_channels, int? bit_rate=None, int? output_num_channels=None, int? output_sample_rate=None) -> int");
150
+ m.def("streaming_encoder_open_file(Tensor(a!) encoder, str filename) -> ()");
151
+ m.def(
152
+ "streaming_encoder_open_file_like(Tensor(a!) encoder, str format, int file_like_context) -> ()");
153
+ m.def(
154
+ "streaming_encoder_add_frames(Tensor(a!) encoder, Tensor frames, int stream_index) -> ()");
155
+ m.def(
156
+ "streaming_encoder_add_samples(Tensor(a!) encoder, Tensor samples, int stream_index) -> ()");
157
+ m.def("set_nvdec_cache_capacity(int capacity) -> ()");
158
+ m.def("get_nvdec_cache_capacity() -> int");
159
+ m.def("_get_nvdec_cache_size(int device_index) -> int");
160
+ m.def("_set_cpp_log_level(int level) -> ()");
161
+ m.def("_get_log_level() -> int");
162
+ m.def("create_wav_decoder_from_file(str filename) -> Tensor");
163
+ m.def("create_wav_decoder_from_tensor(Tensor data) -> Tensor");
164
+ m.def("_create_wav_decoder_from_file_like(int file_like_context) -> Tensor");
165
+ m.def(
166
+ "get_wav_samples_in_range(Tensor(a!) decoder, float start_seconds, float? stop_seconds) -> (Tensor, Tensor)");
167
+ m.def("get_wav_metadata_from_decoder(Tensor(a!) decoder) -> Tensor");
168
+ }
169
+
170
+ namespace {
171
+
172
+ torch::stable::Tensor wrap_decoder_pointer_to_tensor(
173
+ std::unique_ptr<SingleStreamDecoder> unique_decoder) {
174
+ SingleStreamDecoder* decoder = unique_decoder.release();
175
+
176
+ auto deleter = [decoder](void*) { delete decoder; };
177
+ int64_t sizes[] = {static_cast<int64_t>(sizeof(SingleStreamDecoder*))};
178
+ int64_t strides[] = {1};
179
+ torch::stable::Tensor tensor = torch::stable::from_blob(
180
+ decoder,
181
+ {sizes, 1},
182
+ {strides, 1},
183
+ StableDevice(kStableCPU),
184
+ kStableInt64,
185
+ deleter);
186
+ auto video_decoder =
187
+ static_cast<SingleStreamDecoder*>(tensor.mutable_data_ptr());
188
+ STD_TORCH_CHECK(video_decoder == decoder, "videoDecoder != decoder");
189
+ return tensor;
190
+ }
191
+
192
+ torch::stable::Tensor wrap_wav_decoder_pointer_to_tensor(
193
+ std::unique_ptr<WavDecoder> unique_decoder) {
194
+ WavDecoder* decoder = unique_decoder.release();
195
+
196
+ auto deleter = [decoder](void*) { delete decoder; };
197
+ int64_t sizes[] = {static_cast<int64_t>(sizeof(WavDecoder*))};
198
+ int64_t strides[] = {1};
199
+ torch::stable::Tensor tensor = torch::stable::from_blob(
200
+ decoder,
201
+ {sizes, 1},
202
+ {strides, 1},
203
+ StableDevice(kStableCPU),
204
+ kStableInt64,
205
+ deleter);
206
+ auto wav_decoder = static_cast<WavDecoder*>(tensor.mutable_data_ptr());
207
+ STD_TORCH_CHECK(wav_decoder == decoder, "wavDecoder != decoder");
208
+ return tensor;
209
+ }
210
+
211
+ WavDecoder* unwrap_tensor_to_get_wav_decoder(torch::stable::Tensor& tensor) {
212
+ STD_TORCH_CHECK(
213
+ tensor.is_contiguous(),
214
+ "fake decoder tensor must be contiguous! This is an internal error, please report on the torchcodec issue tracker.");
215
+ WavDecoder* decoder = static_cast<WavDecoder*>(tensor.mutable_data_ptr());
216
+ return decoder;
217
+ }
218
+
219
+ SingleStreamDecoder* unwrap_tensor_to_get_decoder(
220
+ torch::stable::Tensor& tensor) {
221
+ STD_TORCH_CHECK(
222
+ tensor.is_contiguous(),
223
+ "fake decoder tensor must be contiguous! This is an internal error, please report on the torchcodec issue tracker.");
224
+ void* buffer = tensor.mutable_data_ptr();
225
+ SingleStreamDecoder* decoder = static_cast<SingleStreamDecoder*>(buffer);
226
+ return decoder;
227
+ }
228
+
229
+ // Generic pointer<->tensor laundering for the building-block handle types
230
+ // (Demuxer / PacketDecoder / ColorConverter / AVPacket / AVFrame). Same trick
231
+ // as wrap_decoder_pointer_to_tensor: the tensor's data pointer IS the raw
232
+ // pointer, and the tensor is the owner. Taking the unique_ptr by value is what
233
+ // makes the ownership transfer explicit at the call site.
234
+ template <typename T, typename D>
235
+ torch::stable::Tensor wrap_pointer_to_tensor(std::unique_ptr<T, D> ptr) {
236
+ D object_deleter = ptr.get_deleter();
237
+ T* raw = ptr.release();
238
+ auto deleter = [raw, object_deleter](void*) { object_deleter(raw); };
239
+ int64_t sizes[] = {static_cast<int64_t>(sizeof(T*))};
240
+ int64_t strides[] = {1};
241
+ return torch::stable::from_blob(
242
+ raw,
243
+ {sizes, 1},
244
+ {strides, 1},
245
+ StableDevice(kStableCPU),
246
+ kStableInt64,
247
+ deleter);
248
+ }
249
+
250
+ template <typename T>
251
+ T* unwrap_tensor_to_pointer(torch::stable::Tensor& tensor) {
252
+ STD_TORCH_CHECK(tensor.is_contiguous(), "handle tensor must be contiguous");
253
+ return static_cast<T*>(tensor.mutable_data_ptr());
254
+ }
255
+
256
+ torch::stable::Tensor wrap_multi_stream_encoder_pointer_to_tensor(
257
+ std::unique_ptr<MultiStreamEncoder> unique_encoder) {
258
+ MultiStreamEncoder* encoder = unique_encoder.release();
259
+ auto deleter = [encoder](void*) { delete encoder; };
260
+ int64_t sizes[] = {static_cast<int64_t>(sizeof(MultiStreamEncoder*))};
261
+ int64_t strides[] = {1};
262
+ torch::stable::Tensor tensor = torch::stable::from_blob(
263
+ encoder,
264
+ {sizes, 1},
265
+ {strides, 1},
266
+ StableDevice(kStableCPU),
267
+ kStableInt64,
268
+ deleter);
269
+ auto multi_stream_encoder =
270
+ static_cast<MultiStreamEncoder*>(tensor.mutable_data_ptr());
271
+ STD_TORCH_CHECK(
272
+ multi_stream_encoder == encoder, "multiStreamEncoder != encoder");
273
+ return tensor;
274
+ }
275
+
276
+ MultiStreamEncoder* unwrap_tensor_to_get_multi_stream_encoder(
277
+ torch::stable::Tensor& tensor) {
278
+ STD_TORCH_CHECK(
279
+ tensor.is_contiguous(),
280
+ "fake encoder tensor must be contiguous! This is an internal error, please report on the torchcodec issue tracker.");
281
+ void* buffer = tensor.mutable_data_ptr();
282
+ MultiStreamEncoder* encoder = static_cast<MultiStreamEncoder*>(buffer);
283
+ return encoder;
284
+ }
285
+
286
+ // The elements of this tuple are all tensors that represent a single frame:
287
+ // 1. The frame data, which is a multidimensional tensor.
288
+ // 2. A single float value for the pts in seconds.
289
+ // 3. A single float value for the duration in seconds.
290
+ // The reason we use Tensors for the second and third values is so we can run
291
+ // under torch.compile().
292
+ using OpsFrameOutput = std::
293
+ tuple<torch::stable::Tensor, torch::stable::Tensor, torch::stable::Tensor>;
294
+
295
+ OpsFrameOutput make_ops_frame_output(FrameOutput& frame) {
296
+ return std::make_tuple(
297
+ frame.data,
298
+ torch::stable::full({}, frame.pts_seconds, kStableFloat64),
299
+ torch::stable::full({}, frame.duration_seconds, kStableFloat64));
300
+ }
301
+
302
+ // All elements of this tuple are tensors of the same leading dimension. The
303
+ // tuple represents the frames for N total frames, where N is the dimension of
304
+ // each stacked tensor. The elments are:
305
+ // 1. Stacked tensor of data for all N frames. Each frame is also a
306
+ // multidimensional tensor.
307
+ // 2. Tensor of N pts values in seconds, where each pts is a single
308
+ // float.
309
+ // 3. Tensor of N durationis in seconds, where each duration is a
310
+ // single float.
311
+ using OpsFrameBatchOutput = std::
312
+ tuple<torch::stable::Tensor, torch::stable::Tensor, torch::stable::Tensor>;
313
+
314
+ OpsFrameBatchOutput make_ops_frame_batch_output(FrameBatchOutput& batch) {
315
+ return std::make_tuple(batch.data, batch.pts_seconds, batch.duration_seconds);
316
+ }
317
+
318
+ // The elements of this tuple are all tensors that represent the concatenation
319
+ // of multiple audio frames:
320
+ // 1. The frames data (concatenated)
321
+ // 2. A single float value for the pts of the first frame, in seconds.
322
+ using OpsAudioFramesOutput =
323
+ std::tuple<torch::stable::Tensor, torch::stable::Tensor>;
324
+
325
+ OpsAudioFramesOutput make_ops_audio_frames_output(
326
+ AudioFramesOutput& audio_frames) {
327
+ return std::make_tuple(
328
+ audio_frames.data,
329
+ torch::stable::full({}, audio_frames.pts_seconds, kStableFloat64));
330
+ }
331
+
332
+ std::string quote_value(const std::string& value) {
333
+ return "\"" + value + "\"";
334
+ }
335
+
336
+ // Helper function to unflatten extra_options, alternating keys and values
337
+ std::map<std::string, std::string> unflatten_extra_options(
338
+ const std::vector<std::string>& opts) {
339
+ std::map<std::string, std::string> options_map;
340
+ for (size_t i = 0; i < opts.size(); i += 2) {
341
+ options_map[opts[i]] = opts[i + 1];
342
+ }
343
+ return options_map;
344
+ }
345
+
346
+ std::string map_to_json(
347
+ const std::map<std::string, std::string>& metadata_map) {
348
+ std::stringstream ss;
349
+ ss << "{\n";
350
+ auto it = metadata_map.begin();
351
+ while (it != metadata_map.end()) {
352
+ ss << "\"" << it->first << "\": " << it->second;
353
+ ++it;
354
+ if (it != metadata_map.end()) {
355
+ ss << ",\n";
356
+ } else {
357
+ ss << "\n";
358
+ }
359
+ }
360
+ ss << "}";
361
+
362
+ return ss.str();
363
+ }
364
+
365
+ // Note [Returning text from ops]
366
+ //
367
+ // Before torch 2.14, every str returned from a stable ABI op is leaked:
368
+ // libtorch converts it to a Python str without freeing the C++ one
369
+ // (pytorch/pytorch#190493). We support older torch versions, so ops that can
370
+ // run more than once per process don't return str. Instead:
371
+ //
372
+ // - Values of an FFmpeg enum (pixel format, color space, packet side data
373
+ // type...) are returned as ints, and Python names them with
374
+ // _blocks_get_ffmpeg_enum_name(). Python caches its results, so each distinct
375
+ // value leaks at most once per process. The names can't be hardcoded in
376
+ // Python, as the int values can differ between FFmpeg versions (e.g. FFmpeg 5
377
+ // removed AV_PIX_FMT_XVMC, shifting all the pixel formats after it).
378
+ // - Free-form text (JSON metadata, channel layouts...) is returned as UTF-8
379
+ // bytes in a uint8 tensor by string_to_tensor(), and decoded in Python.
380
+ //
381
+ // test_no_op_returns_str enforces this. The few ops it allows to return str are
382
+ // cached or only meant for debugging.
383
+ //
384
+ // Ops taking str arguments have a similar leak (pytorch/pytorch#191340), but
385
+ // the leaking code there is torch header code compiled into our library: it
386
+ // depends on the torch version we build against, not on the one we run with.
387
+ // There is nothing to work around here, as our wheels are built against torch
388
+ // >= 2.14, which doesn't have the issue.
389
+ //
390
+ // Once the minimum supported torch version is 2.14, all of this can go away and
391
+ // these ops can return str again.
392
+ torch::stable::Tensor string_to_tensor(std::string_view str) {
393
+ torch::stable::Tensor tensor =
394
+ torch::stable::empty({static_cast<int64_t>(str.size())}, kStableUInt8);
395
+ std::memcpy(tensor.mutable_data_ptr<uint8_t>(), str.data(), str.size());
396
+ return tensor;
397
+ }
398
+
399
+ std::optional<torch::stable::Tensor> optional_string_to_tensor(
400
+ const std::optional<std::string>& str) {
401
+ if (!str.has_value()) {
402
+ return std::nullopt;
403
+ }
404
+ return string_to_tensor(*str);
405
+ }
406
+
407
+ torch::stable::Tensor map_to_json_tensor(
408
+ const std::map<std::string, std::string>& metadata_map) {
409
+ return string_to_tensor(map_to_json(metadata_map));
410
+ }
411
+
412
+ SeekMode seek_mode_from_string(std::string_view seek_mode) {
413
+ if (seek_mode == "exact") {
414
+ return SeekMode::exact;
415
+ } else if (seek_mode == "approximate") {
416
+ return SeekMode::approximate;
417
+ } else if (seek_mode == "custom_frame_mappings") {
418
+ return SeekMode::custom_frame_mappings;
419
+ } else {
420
+ STD_TORCH_CHECK(false, "Invalid seek mode: " + std::string(seek_mode));
421
+ }
422
+ }
423
+
424
+ void write_fallback_based_metadata(
425
+ std::map<std::string, std::string>& map,
426
+ const StreamMetadata& stream_metadata,
427
+ SeekMode seek_mode) {
428
+ auto duration_seconds = stream_metadata.get_duration_seconds(seek_mode);
429
+ if (duration_seconds.has_value()) {
430
+ map["durationSeconds"] = fmt::to_string(duration_seconds.value());
431
+ }
432
+
433
+ auto num_frames = stream_metadata.get_num_frames(seek_mode);
434
+ if (num_frames.has_value()) {
435
+ map["numFrames"] = std::to_string(num_frames.value());
436
+ }
437
+
438
+ double begin_stream_seconds =
439
+ stream_metadata.get_begin_stream_seconds(seek_mode);
440
+ map["beginStreamSeconds"] = fmt::to_string(begin_stream_seconds);
441
+
442
+ auto end_stream_seconds = stream_metadata.get_end_stream_seconds(seek_mode);
443
+ if (end_stream_seconds.has_value()) {
444
+ map["endStreamSeconds"] = fmt::to_string(end_stream_seconds.value());
445
+ }
446
+
447
+ auto average_fps = stream_metadata.get_average_fps(seek_mode);
448
+ if (average_fps.has_value()) {
449
+ map["averageFps"] = fmt::to_string(average_fps.value());
450
+ }
451
+ }
452
+
453
+ int checked_to_positive_int(const std::string& str) {
454
+ int ret = 0;
455
+ try {
456
+ ret = std::stoi(str);
457
+ } catch (const std::invalid_argument&) {
458
+ STD_TORCH_CHECK(false, "String cannot be converted to an int:" + str);
459
+ } catch (const std::out_of_range&) {
460
+ STD_TORCH_CHECK(false, "String would become integer out of range:" + str);
461
+ }
462
+ STD_TORCH_CHECK(ret > 0, "String must be a positive integer:" + str);
463
+ return ret;
464
+ }
465
+
466
+ int checked_to_non_negative_int(const std::string& str) {
467
+ int ret = 0;
468
+ try {
469
+ ret = std::stoi(str);
470
+ } catch (const std::invalid_argument&) {
471
+ STD_TORCH_CHECK(false, "String cannot be converted to an int:" + str);
472
+ } catch (const std::out_of_range&) {
473
+ STD_TORCH_CHECK(false, "String would become integer out of range:" + str);
474
+ }
475
+ STD_TORCH_CHECK(ret >= 0, "String must be a non-negative integer:" + str);
476
+ return ret;
477
+ }
478
+
479
+ // Resize transform specs take the form:
480
+ //
481
+ // "resize, <height>, <width>"
482
+ //
483
+ // Where "resize" is the string literal and <height> and <width> are positive
484
+ // integers.
485
+ Transform* make_resize_transform(
486
+ const std::vector<std::string>& resize_transform_spec) {
487
+ STD_TORCH_CHECK(
488
+ resize_transform_spec.size() == 3,
489
+ "resizeTransformSpec must have 3 elements including its name");
490
+ int height = checked_to_positive_int(resize_transform_spec[1]);
491
+ int width = checked_to_positive_int(resize_transform_spec[2]);
492
+ return new ResizeTransform(FrameDims(height, width));
493
+ }
494
+
495
+ // Crop transform specs take the form:
496
+ //
497
+ // "crop, <height>, <width>, <x>, <y>"
498
+ //
499
+ // Where "crop" is the string literal and <height>, <width>, <x> and <y> are
500
+ // positive integers. <x> and <y> are the x and y coordinates of the top left
501
+ // corner of the crop. Note that we follow the PyTorch convention of (height,
502
+ // width) for specifying image dimensions; FFmpeg uses (width, height).
503
+ Transform* make_crop_transform(
504
+ const std::vector<std::string>& crop_transform_spec) {
505
+ STD_TORCH_CHECK(
506
+ crop_transform_spec.size() == 5,
507
+ "cropTransformSpec must have 5 elements including its name");
508
+ int height = checked_to_positive_int(crop_transform_spec[1]);
509
+ int width = checked_to_positive_int(crop_transform_spec[2]);
510
+ int x = checked_to_non_negative_int(crop_transform_spec[3]);
511
+ int y = checked_to_non_negative_int(crop_transform_spec[4]);
512
+ return new CropTransform(FrameDims(height, width), x, y);
513
+ }
514
+
515
+ // CenterCrop transform specs take the form:
516
+ //
517
+ // "center_crop, <height>, <width>"
518
+ //
519
+ // Where "center_crop" is the string literal and <height>, <width> are
520
+ // positive integers. Note that we follow the PyTorch convention of (height,
521
+ // width) for specifying image dimensions; FFmpeg uses (width, height).
522
+ Transform* make_center_crop_transform(
523
+ const std::vector<std::string>& crop_transform_spec) {
524
+ STD_TORCH_CHECK(
525
+ crop_transform_spec.size() == 3,
526
+ "cropTransformSpec must have 3 elements including its name");
527
+ int height = checked_to_positive_int(crop_transform_spec[1]);
528
+ int width = checked_to_positive_int(crop_transform_spec[2]);
529
+ return new CropTransform(FrameDims(height, width));
530
+ }
531
+
532
+ std::vector<std::string> split(const std::string& str, char delimiter) {
533
+ std::vector<std::string> tokens;
534
+ std::string token;
535
+ std::istringstream token_stream(str);
536
+ while (std::getline(token_stream, token, delimiter)) {
537
+ tokens.push_back(token);
538
+ }
539
+ return tokens;
540
+ }
541
+
542
+ // The transformSpecsRaw string is always in the format:
543
+ //
544
+ // "name1, param1, param2, ...; name2, param1, param2, ...; ..."
545
+ //
546
+ // Where "nameX" is the name of the transform, and "paramX" are the parameters.
547
+ std::vector<Transform*> make_transforms(
548
+ const std::string& transform_specs_raw) {
549
+ std::vector<Transform*> transforms;
550
+ std::vector<std::string> transform_specs = split(transform_specs_raw, ';');
551
+ for (const std::string& transform_spec_raw : transform_specs) {
552
+ std::vector<std::string> transform_spec = split(transform_spec_raw, ',');
553
+ STD_TORCH_CHECK(
554
+ transform_spec.size() >= 1,
555
+ "Invalid transform spec: " + transform_spec_raw);
556
+
557
+ auto name = transform_spec[0];
558
+ if (name == "resize") {
559
+ transforms.push_back(make_resize_transform(transform_spec));
560
+ } else if (name == "crop") {
561
+ transforms.push_back(make_crop_transform(transform_spec));
562
+ } else if (name == "center_crop") {
563
+ transforms.push_back(make_center_crop_transform(transform_spec));
564
+ } else {
565
+ STD_TORCH_CHECK(false, "Invalid transform name: " + name);
566
+ }
567
+ }
568
+ return transforms;
569
+ }
570
+
571
+ } // namespace
572
+
573
+ // ==============================
574
+ // Implementations for the operators
575
+ // ==============================
576
+
577
+ // Create a SingleStreamDecoder from file and wrap the pointer in a tensor.
578
+ torch::stable::Tensor create_from_file(
579
+ std::string filename,
580
+ std::optional<std::string> seek_mode = std::nullopt) {
581
+ SeekMode real_seek = SeekMode::exact;
582
+ if (seek_mode.has_value()) {
583
+ real_seek = seek_mode_from_string(seek_mode.value());
584
+ }
585
+
586
+ std::unique_ptr<SingleStreamDecoder> unique_decoder =
587
+ std::make_unique<SingleStreamDecoder>(filename, real_seek);
588
+
589
+ return wrap_decoder_pointer_to_tensor(std::move(unique_decoder));
590
+ }
591
+
592
+ // Create a SingleStreamDecoder from the actual bytes of a video and wrap the
593
+ // pointer in a tensor. The SingleStreamDecoder will decode the provided bytes.
594
+ torch::stable::Tensor create_from_tensor(
595
+ const torch::stable::Tensor& video_tensor,
596
+ std::optional<std::string> seek_mode = std::nullopt) {
597
+ STD_TORCH_CHECK(
598
+ video_tensor.is_contiguous(), "video_tensor must be contiguous");
599
+ STD_TORCH_CHECK(
600
+ video_tensor.scalar_type() == kStableUInt8,
601
+ "video_tensor must be kUInt8");
602
+
603
+ SeekMode real_seek = SeekMode::exact;
604
+ if (seek_mode.has_value()) {
605
+ real_seek = seek_mode_from_string(seek_mode.value());
606
+ }
607
+
608
+ auto avio_context_holder = std::make_unique<AVIOContextHolder>(
609
+ std::make_unique<TensorReadIO>(video_tensor), /*is_for_writing=*/false);
610
+
611
+ std::unique_ptr<SingleStreamDecoder> unique_decoder =
612
+ std::make_unique<SingleStreamDecoder>(
613
+ std::move(avio_context_holder), real_seek);
614
+ return wrap_decoder_pointer_to_tensor(std::move(unique_decoder));
615
+ }
616
+
617
+ torch::stable::Tensor _create_from_file_like(
618
+ int64_t file_like_context,
619
+ std::optional<std::string> seek_mode) {
620
+ auto io = adopt_file_like_context(file_like_context);
621
+ auto avio_context_holder = std::make_unique<AVIOContextHolder>(
622
+ std::move(io),
623
+ /*is_for_writing=*/false);
624
+
625
+ SeekMode real_seek = SeekMode::exact;
626
+ if (seek_mode.has_value()) {
627
+ real_seek = seek_mode_from_string(seek_mode.value());
628
+ }
629
+
630
+ std::unique_ptr<SingleStreamDecoder> unique_decoder =
631
+ std::make_unique<SingleStreamDecoder>(
632
+ std::move(avio_context_holder), real_seek);
633
+ return wrap_decoder_pointer_to_tensor(std::move(unique_decoder));
634
+ }
635
+
636
+ OutputDtypeConfig parse_output_dtype_config(const std::string& output_dtype) {
637
+ if (output_dtype == "uint8") {
638
+ return OutputDtypeConfig::UINT8;
639
+ } else if (output_dtype == "float32") {
640
+ return OutputDtypeConfig::FLOAT32;
641
+ } else if (output_dtype == "auto") {
642
+ return OutputDtypeConfig::AUTO;
643
+ }
644
+ STD_TORCH_CHECK(
645
+ false,
646
+ "Invalid output_dtype=",
647
+ output_dtype,
648
+ ". Supported values are: uint8, float32, auto.");
649
+ }
650
+
651
+ void _add_video_stream(
652
+ torch::stable::Tensor& decoder,
653
+ std::optional<int64_t> num_threads = std::nullopt,
654
+ std::optional<std::string> dimension_order = std::nullopt,
655
+ std::optional<int64_t> stream_index = std::nullopt,
656
+ std::string device = "cpu",
657
+ std::string device_variant = "default",
658
+ std::string transform_specs = "",
659
+ std::optional<torch::stable::Tensor> custom_frame_mappings_pts =
660
+ std::nullopt,
661
+ std::optional<torch::stable::Tensor> custom_frame_mappings_duration =
662
+ std::nullopt,
663
+ std::optional<torch::stable::Tensor>
664
+ custom_frame_mappings_keyframe_indices = std::nullopt,
665
+ std::optional<std::string> color_conversion_library = std::nullopt,
666
+ std::string output_dtype = "uint8") {
667
+ VideoStreamOptions video_stream_options;
668
+ video_stream_options.ffmpeg_thread_count = num_threads;
669
+
670
+ video_stream_options.output_dtype_config =
671
+ parse_output_dtype_config(output_dtype);
672
+
673
+ if (dimension_order.has_value()) {
674
+ STD_TORCH_CHECK(
675
+ *dimension_order == "NHWC" || *dimension_order == "NCHW",
676
+ "dimension_order must be NHWC or NCHW");
677
+ video_stream_options.dimension_order = std::move(*dimension_order);
678
+ }
679
+ if (color_conversion_library.has_value()) {
680
+ const std::string& std_color_conversion_library =
681
+ color_conversion_library.value();
682
+ if (std_color_conversion_library == "filtergraph") {
683
+ video_stream_options.color_conversion_library =
684
+ ColorConversionLibrary::FILTERGRAPH;
685
+ } else if (std_color_conversion_library == "swscale") {
686
+ video_stream_options.color_conversion_library =
687
+ ColorConversionLibrary::SWSCALE;
688
+ } else {
689
+ STD_TORCH_CHECK(
690
+ false,
691
+ "Invalid color_conversion_library=",
692
+ std_color_conversion_library,
693
+ ". color_conversion_library must be either filtergraph or swscale.");
694
+ }
695
+ }
696
+
697
+ validate_device_interface(device, device_variant);
698
+
699
+ video_stream_options.device = StableDevice(std::move(device));
700
+ video_stream_options.device_variant = std::move(device_variant);
701
+
702
+ std::vector<Transform*> transforms =
703
+ make_transforms(std::move(transform_specs));
704
+
705
+ bool has_pts = custom_frame_mappings_pts.has_value();
706
+ bool has_duration = custom_frame_mappings_duration.has_value();
707
+ bool has_keyframe_indices =
708
+ custom_frame_mappings_keyframe_indices.has_value();
709
+ STD_TORCH_CHECK(
710
+ (has_pts == has_duration) && (has_duration == has_keyframe_indices),
711
+ "custom_frame_mappings_pts, custom_frame_mappings_duration, and "
712
+ "custom_frame_mappings_keyframe_indices must all be provided or all be "
713
+ "None. This is a bug in TorchCodec, please report it.");
714
+
715
+ std::optional<SingleStreamDecoder::FrameMappings> converted_mappings = has_pts
716
+ ? std::make_optional(SingleStreamDecoder::FrameMappings{
717
+ std::move(*custom_frame_mappings_pts),
718
+ std::move(*custom_frame_mappings_keyframe_indices),
719
+ std::move(*custom_frame_mappings_duration)})
720
+ : std::nullopt;
721
+ auto video_decoder = unwrap_tensor_to_get_decoder(decoder);
722
+ video_decoder->add_video_stream(
723
+ stream_index.value_or(-1),
724
+ transforms,
725
+ video_stream_options,
726
+ converted_mappings);
727
+ }
728
+
729
+ // Add a new video stream at `stream_index` using the provided options.
730
+ void add_video_stream(
731
+ torch::stable::Tensor& decoder,
732
+ std::optional<int64_t> num_threads = std::nullopt,
733
+ std::optional<std::string> dimension_order = std::nullopt,
734
+ std::optional<int64_t> stream_index = std::nullopt,
735
+ std::string device = "cpu",
736
+ std::string device_variant = "default",
737
+ std::string transform_specs = "",
738
+ std::optional<torch::stable::Tensor> custom_frame_mappings_pts =
739
+ std::nullopt,
740
+ std::optional<torch::stable::Tensor> custom_frame_mappings_duration =
741
+ std::nullopt,
742
+ std::optional<torch::stable::Tensor>
743
+ custom_frame_mappings_keyframe_indices = std::nullopt,
744
+ std::string output_dtype = "uint8") {
745
+ _add_video_stream(
746
+ decoder,
747
+ num_threads,
748
+ std::move(dimension_order),
749
+ stream_index,
750
+ std::move(device),
751
+ std::move(device_variant),
752
+ std::move(transform_specs),
753
+ std::move(custom_frame_mappings_pts),
754
+ std::move(custom_frame_mappings_duration),
755
+ std::move(custom_frame_mappings_keyframe_indices),
756
+ /*color_conversion_library=*/std::nullopt,
757
+ std::move(output_dtype));
758
+ }
759
+
760
+ void add_audio_stream(
761
+ torch::stable::Tensor& decoder,
762
+ std::optional<int64_t> stream_index = std::nullopt,
763
+ std::optional<int64_t> sample_rate = std::nullopt,
764
+ std::optional<int64_t> num_channels = std::nullopt) {
765
+ AudioStreamOptions audio_stream_options;
766
+ audio_stream_options.sample_rate = sample_rate;
767
+ audio_stream_options.num_channels = num_channels;
768
+
769
+ auto video_decoder = unwrap_tensor_to_get_decoder(decoder);
770
+ video_decoder->add_audio_stream(
771
+ stream_index.value_or(-1), audio_stream_options);
772
+ }
773
+
774
+ // Seek to a particular presentation timestamp in the video in seconds.
775
+ void seek_to_pts(torch::stable::Tensor& decoder, double seconds) {
776
+ auto video_decoder =
777
+ static_cast<SingleStreamDecoder*>(decoder.mutable_data_ptr());
778
+ video_decoder->set_cursor_pts_in_seconds(seconds);
779
+ }
780
+
781
+ // Get the next frame from the video as a tuple that has the frame data, pts and
782
+ // duration as tensors.
783
+ OpsFrameOutput get_next_frame(torch::stable::Tensor& decoder) {
784
+ auto video_decoder = unwrap_tensor_to_get_decoder(decoder);
785
+ FrameOutput result;
786
+ try {
787
+ result = video_decoder->get_next_frame();
788
+ } catch (const SingleStreamDecoder::EndOfFileException& e) {
789
+ STABLE_CHECK_INDEX(false, e.what());
790
+ }
791
+ return make_ops_frame_output(result);
792
+ }
793
+
794
+ // Return the frame that is visible at a given timestamp in seconds. Each frame
795
+ // in FFMPEG has a presentation timestamp and a duration. The frame visible at a
796
+ // given timestamp T has T >= PTS and T < PTS + Duration.
797
+ OpsFrameOutput get_frame_at_pts(
798
+ torch::stable::Tensor& decoder,
799
+ double seconds) {
800
+ auto video_decoder = unwrap_tensor_to_get_decoder(decoder);
801
+ FrameOutput result;
802
+ try {
803
+ result = video_decoder->get_frame_played_at(seconds);
804
+ } catch (const SingleStreamDecoder::EndOfFileException& e) {
805
+ STABLE_CHECK_INDEX(false, e.what());
806
+ }
807
+ return make_ops_frame_output(result);
808
+ }
809
+
810
+ // Return the frame that is visible at a given index in the video.
811
+ OpsFrameOutput get_frame_at_index(
812
+ torch::stable::Tensor& decoder,
813
+ int64_t frame_index) {
814
+ auto video_decoder = unwrap_tensor_to_get_decoder(decoder);
815
+ auto result = video_decoder->get_frame_at_index(frame_index);
816
+ return make_ops_frame_output(result);
817
+ }
818
+
819
+ // Return the frames at given indices for a given stream
820
+ OpsFrameBatchOutput get_frames_at_indices(
821
+ torch::stable::Tensor& decoder,
822
+ const torch::stable::Tensor& frame_indices) {
823
+ auto video_decoder = unwrap_tensor_to_get_decoder(decoder);
824
+ auto result = video_decoder->get_frames_at_indices(frame_indices);
825
+ return make_ops_frame_batch_output(result);
826
+ }
827
+
828
+ // Return the frames inside a range as a single stacked Tensor. The range is
829
+ // defined as [start, stop).
830
+ OpsFrameBatchOutput get_frames_in_range(
831
+ torch::stable::Tensor& decoder,
832
+ int64_t start,
833
+ int64_t stop,
834
+ std::optional<int64_t> step = std::nullopt) {
835
+ auto video_decoder = unwrap_tensor_to_get_decoder(decoder);
836
+ auto result =
837
+ video_decoder->get_frames_in_range(start, stop, step.value_or(1));
838
+ return make_ops_frame_batch_output(result);
839
+ }
840
+
841
+ // Return the frames at given ptss for a given stream
842
+ OpsFrameBatchOutput get_frames_by_pts(
843
+ torch::stable::Tensor& decoder,
844
+ const torch::stable::Tensor& timestamps) {
845
+ auto video_decoder = unwrap_tensor_to_get_decoder(decoder);
846
+ auto result = video_decoder->get_frames_played_at(timestamps);
847
+ return make_ops_frame_batch_output(result);
848
+ }
849
+
850
+ // Return the frames inside the range as a single stacked Tensor. The range is
851
+ // defined as [start_seconds, stop_seconds). The frames are stacked in pts
852
+ // order.
853
+ // If fps is specified, frames are resampled to match the target frame
854
+ // rate by duplicating or dropping frames as necessary.
855
+ OpsFrameBatchOutput get_frames_by_pts_in_range(
856
+ torch::stable::Tensor& decoder,
857
+ double start_seconds,
858
+ double stop_seconds,
859
+ std::optional<double> fps = std::nullopt) {
860
+ auto video_decoder = unwrap_tensor_to_get_decoder(decoder);
861
+ auto result = video_decoder->get_frames_played_in_range(
862
+ start_seconds, stop_seconds, fps);
863
+ return make_ops_frame_batch_output(result);
864
+ }
865
+
866
+ OpsAudioFramesOutput get_frames_by_pts_in_range_audio(
867
+ torch::stable::Tensor& decoder,
868
+ double start_seconds,
869
+ std::optional<double> stop_seconds = std::nullopt) {
870
+ auto video_decoder = unwrap_tensor_to_get_decoder(decoder);
871
+ auto result = video_decoder->get_frames_played_in_range_audio(
872
+ start_seconds, stop_seconds);
873
+ return make_ops_audio_frames_output(result);
874
+ }
875
+
876
+ // ==============================
877
+ // Low-level API ops (torchcodec.decoders, implemented in decoders/_blocks)
878
+ // ==============================
879
+
880
+ std::optional<int> to_optional_int(std::optional<int64_t> value) {
881
+ if (!value.has_value()) {
882
+ return std::nullopt;
883
+ }
884
+ return static_cast<int>(value.value());
885
+ }
886
+
887
+ AVMediaType parse_media_type(const std::string& media_type) {
888
+ if (media_type == "video") {
889
+ return AVMEDIA_TYPE_VIDEO;
890
+ }
891
+ STD_TORCH_CHECK(
892
+ media_type == "audio",
893
+ "Invalid media_type: '",
894
+ media_type,
895
+ "'. Expected 'video' or 'audio'.");
896
+ return AVMEDIA_TYPE_AUDIO;
897
+ }
898
+
899
+ torch::stable::Tensor _blocks_create_demuxer_from_file(std::string filename) {
900
+ auto demuxer = std::make_unique<Demuxer>(filename);
901
+ return wrap_pointer_to_tensor<Demuxer>(std::move(demuxer));
902
+ }
903
+
904
+ torch::stable::Tensor _blocks_create_demuxer_from_tensor(
905
+ const torch::stable::Tensor& video_tensor) {
906
+ STD_TORCH_CHECK(
907
+ video_tensor.is_contiguous(), "video_tensor must be contiguous");
908
+ STD_TORCH_CHECK(
909
+ video_tensor.scalar_type() == kStableUInt8,
910
+ "video_tensor must be kUInt8");
911
+
912
+ auto avio_context_holder = std::make_unique<AVIOContextHolder>(
913
+ std::make_unique<TensorReadIO>(video_tensor), /*is_for_writing=*/false);
914
+ auto demuxer = std::make_unique<Demuxer>(std::move(avio_context_holder));
915
+ return wrap_pointer_to_tensor<Demuxer>(std::move(demuxer));
916
+ }
917
+
918
+ torch::stable::Tensor _blocks_create_demuxer_from_file_like(
919
+ int64_t file_like_context) {
920
+ auto io = adopt_file_like_context(file_like_context);
921
+
922
+ auto avio_context_holder = std::make_unique<AVIOContextHolder>(
923
+ std::move(io),
924
+ /*is_for_writing=*/false);
925
+ auto demuxer = std::make_unique<Demuxer>(std::move(avio_context_holder));
926
+ return wrap_pointer_to_tensor<Demuxer>(std::move(demuxer));
927
+ }
928
+
929
+ torch::stable::Tensor _blocks_demuxer_get_audio_video_stream_indices(
930
+ torch::stable::Tensor& demuxer) {
931
+ return unwrap_tensor_to_pointer<Demuxer>(demuxer)
932
+ ->get_audio_video_stream_indices();
933
+ }
934
+
935
+ // (stream index, is video) of the stream that is now being followed. The
936
+ // media type comes back so the caller doesn't have to ask for it separately
937
+ // when it identified the stream by index. It's a bool rather than a str, see
938
+ // Note [Returning text from ops].
939
+ std::tuple<int64_t, bool> _blocks_demuxer_add_stream(
940
+ torch::stable::Tensor& demuxer,
941
+ std::optional<int64_t> stream_index,
942
+ std::optional<std::string> media_type) {
943
+ auto [index, type] = unwrap_tensor_to_pointer<Demuxer>(demuxer)->add_stream(
944
+ to_optional_int(stream_index),
945
+ media_type.has_value()
946
+ ? std::optional<AVMediaType>(parse_media_type(*media_type))
947
+ : std::nullopt);
948
+ return {static_cast<int64_t>(index), type == AVMEDIA_TYPE_VIDEO};
949
+ }
950
+
951
+ // (packet_handle, is_eof, stream_index). On EOF the packet_handle is a dummy
952
+ // tensor that must not be used and stream_index is -1. Native bool avoids
953
+ // per-frame .item() overhead in Python.
954
+ using OpsPacketOutput = std::tuple<torch::stable::Tensor, bool, int64_t>;
955
+
956
+ OpsPacketOutput _blocks_demuxer_next_packet(torch::stable::Tensor& demuxer) {
957
+ Demuxer* demuxer_ptr = unwrap_tensor_to_pointer<Demuxer>(demuxer);
958
+ UniqueAVPacket packet = demuxer_ptr->next_packet();
959
+ if (packet == nullptr) {
960
+ return std::make_tuple(torch::stable::full({1}, 0, kStableInt64), true, -1);
961
+ }
962
+ int64_t stream_index = packet->stream_index;
963
+ return std::make_tuple(
964
+ wrap_pointer_to_tensor(std::move(packet)), false, stream_index);
965
+ }
966
+
967
+ void _blocks_demuxer_seek(
968
+ torch::stable::Tensor& demuxer,
969
+ double seconds,
970
+ std::optional<int64_t> stream_index) {
971
+ unwrap_tensor_to_pointer<Demuxer>(demuxer)->seek(
972
+ seconds, to_optional_int(stream_index));
973
+ }
974
+
975
+ // (pts, duration, is_key_frame, time_base_num, time_base_den). pts and duration
976
+ // are int64 [N] in time-base units rather than seconds
977
+ using OpsScanOutput = std::tuple<
978
+ torch::stable::Tensor,
979
+ torch::stable::Tensor,
980
+ torch::stable::Tensor,
981
+ int64_t,
982
+ int64_t>;
983
+
984
+ OpsScanOutput _blocks_demuxer_scan(
985
+ torch::stable::Tensor& demuxer,
986
+ std::optional<int64_t> stream_index) {
987
+ FrameIndex index = unwrap_tensor_to_pointer<Demuxer>(demuxer)->scan(
988
+ to_optional_int(stream_index));
989
+ return std::make_tuple(
990
+ index.pts,
991
+ index.duration,
992
+ index.is_key_frame,
993
+ static_cast<int64_t>(index.time_base.num),
994
+ static_cast<int64_t>(index.time_base.den));
995
+ }
996
+
997
+ namespace {
998
+ // The codec parameters fields are None when they are at their FFmpeg default.
999
+ std::optional<int64_t> unless_default(
1000
+ int64_t value,
1001
+ int64_t default_value = 0) {
1002
+ if (value == default_value) {
1003
+ return std::nullopt;
1004
+ }
1005
+ return value;
1006
+ }
1007
+
1008
+ // [num, den], the schema's spelling of an AVRational.
1009
+ std::optional<std::vector<int64_t>> unless_unset(const AVRational& value) {
1010
+ if (value.num == 0 || value.den == 0) {
1011
+ return std::nullopt;
1012
+ }
1013
+ return std::vector<int64_t>{value.num, value.den};
1014
+ }
1015
+
1016
+ // FFmpeg's *_name() functions return null for invalid values.
1017
+ std::optional<std::string> to_optional_string(const char* name) {
1018
+ if (name == nullptr) {
1019
+ return std::nullopt;
1020
+ }
1021
+ return std::string(name);
1022
+ }
1023
+
1024
+ torch::stable::Tensor bytes_to_tensor(const uint8_t* data, size_t size) {
1025
+ torch::stable::Tensor tensor =
1026
+ torch::stable::empty({static_cast<int64_t>(size)}, kStableUInt8);
1027
+ std::memcpy(tensor.mutable_data_ptr<uint8_t>(), data, size);
1028
+ return tensor;
1029
+ }
1030
+ } // namespace
1031
+
1032
+ using OpsCodecParametersOutput = std::tuple<
1033
+ torch::stable::Tensor, // codec
1034
+ std::vector<int64_t>, // time_base
1035
+ std::optional<torch::stable::Tensor>, // extradata
1036
+ std::optional<int64_t>, // codec_tag
1037
+ std::optional<int64_t>, // profile
1038
+ std::optional<int64_t>, // level
1039
+ std::optional<int64_t>, // bit_rate
1040
+ std::optional<int64_t>, // bits_per_coded_sample
1041
+ std::optional<int64_t>, // bits_per_raw_sample
1042
+ std::vector<torch::stable::Tensor>, // coded_side_data_names
1043
+ std::vector<torch::stable::Tensor>, // coded_side_data_values
1044
+ std::optional<int64_t>, // width
1045
+ std::optional<int64_t>, // height
1046
+ std::optional<torch::stable::Tensor>, // pixel_format
1047
+ std::optional<std::vector<int64_t>>, // sample_aspect_ratio
1048
+ std::optional<std::vector<int64_t>>, // framerate
1049
+ std::optional<std::vector<int64_t>>, // r_frame_rate
1050
+ std::optional<torch::stable::Tensor>, // field_order
1051
+ std::optional<torch::stable::Tensor>, // color_range
1052
+ std::optional<torch::stable::Tensor>, // color_primaries
1053
+ std::optional<torch::stable::Tensor>, // color_transfer_characteristic
1054
+ std::optional<torch::stable::Tensor>, // color_space
1055
+ std::optional<torch::stable::Tensor>, // chroma_location
1056
+ std::optional<int64_t>, // video_delay
1057
+ std::optional<torch::stable::Tensor>, // sample_format
1058
+ std::optional<int64_t>, // sample_rate
1059
+ std::optional<torch::stable::Tensor>, // channel_layout
1060
+ std::optional<int64_t>, // block_align
1061
+ std::optional<int64_t>, // frame_size
1062
+ std::optional<int64_t>, // initial_padding
1063
+ std::optional<int64_t>, // trailing_padding
1064
+ std::optional<int64_t>, // seek_preroll
1065
+ std::optional<torch::stable::Tensor>>; // container_format
1066
+
1067
+ // Enums are returned as FFmpeg's names for them. All text is returned as
1068
+ // tensors, see Note [Returning text from ops].
1069
+ OpsCodecParametersOutput _blocks_demuxer_get_codec_parameters(
1070
+ torch::stable::Tensor& demuxer,
1071
+ int64_t stream_index) {
1072
+ CodecParameters params =
1073
+ unwrap_tensor_to_pointer<Demuxer>(demuxer)->get_codec_parameters(
1074
+ static_cast<int>(stream_index));
1075
+ const AVCodecParameters& codecpar = *params.codecpar;
1076
+
1077
+ OpsCodecParametersOutput output;
1078
+ auto& [codec, time_base, extradata, codec_tag, profile, level, bit_rate, bits_per_coded_sample, bits_per_raw_sample, coded_side_data_names, coded_side_data_values, width, height, pixel_format, sample_aspect_ratio, framerate, r_frame_rate, field_order, color_range, color_primaries, color_transfer_characteristic, color_space, chroma_location, video_delay, sample_format, sample_rate, channel_layout, block_align, frame_size, initial_padding, trailing_padding, seek_preroll, container_format] =
1079
+ output;
1080
+
1081
+ codec = string_to_tensor(avcodec_get_name(codecpar.codec_id));
1082
+ time_base = {params.time_base.num, params.time_base.den};
1083
+ if (codecpar.extradata_size > 0) {
1084
+ extradata = bytes_to_tensor(codecpar.extradata, codecpar.extradata_size);
1085
+ }
1086
+ codec_tag = unless_default(codecpar.codec_tag);
1087
+ profile = unless_default(codecpar.profile, kUnknownProfileOrLevel);
1088
+ level = unless_default(codecpar.level, kUnknownProfileOrLevel);
1089
+ bit_rate = unless_default(codecpar.bit_rate);
1090
+ bits_per_coded_sample = unless_default(codecpar.bits_per_coded_sample);
1091
+ bits_per_raw_sample = unless_default(codecpar.bits_per_raw_sample);
1092
+ for (const AVPacketSideData& side_data : params.get_stream_side_data()) {
1093
+ const char* name = av_packet_side_data_name(side_data.type);
1094
+ // A type this FFmpeg can't name is a type it doesn't know what to do with
1095
+ // either, so there's nothing a decoder would read from it.
1096
+ if (name != nullptr) {
1097
+ coded_side_data_names.push_back(string_to_tensor(name));
1098
+ coded_side_data_values.push_back(
1099
+ bytes_to_tensor(side_data.data, side_data.size));
1100
+ }
1101
+ }
1102
+
1103
+ if (codecpar.codec_type == AVMEDIA_TYPE_VIDEO) {
1104
+ width = unless_default(codecpar.width);
1105
+ height = unless_default(codecpar.height);
1106
+ pixel_format = optional_string_to_tensor(to_optional_string(
1107
+ av_get_pix_fmt_name(static_cast<AVPixelFormat>(codecpar.format))));
1108
+ sample_aspect_ratio = unless_unset(codecpar.sample_aspect_ratio);
1109
+ framerate = unless_unset(get_framerate(codecpar));
1110
+ r_frame_rate = unless_unset(params.r_frame_rate);
1111
+ field_order = optional_string_to_tensor(
1112
+ to_optional_string(get_field_order_name(codecpar.field_order)));
1113
+ if (codecpar.color_range != AVCOL_RANGE_UNSPECIFIED) {
1114
+ color_range = optional_string_to_tensor(
1115
+ to_optional_string(av_color_range_name(codecpar.color_range)));
1116
+ }
1117
+ if (codecpar.color_primaries != AVCOL_PRI_UNSPECIFIED) {
1118
+ color_primaries = optional_string_to_tensor(to_optional_string(
1119
+ av_color_primaries_name(codecpar.color_primaries)));
1120
+ }
1121
+ if (codecpar.color_trc != AVCOL_TRC_UNSPECIFIED) {
1122
+ color_transfer_characteristic = optional_string_to_tensor(
1123
+ to_optional_string(av_color_transfer_name(codecpar.color_trc)));
1124
+ }
1125
+ if (codecpar.color_space != AVCOL_SPC_UNSPECIFIED) {
1126
+ color_space = optional_string_to_tensor(
1127
+ to_optional_string(av_color_space_name(codecpar.color_space)));
1128
+ }
1129
+ if (codecpar.chroma_location != AVCHROMA_LOC_UNSPECIFIED) {
1130
+ chroma_location = optional_string_to_tensor(to_optional_string(
1131
+ av_chroma_location_name(codecpar.chroma_location)));
1132
+ }
1133
+ video_delay = unless_default(codecpar.video_delay);
1134
+ } else if (codecpar.codec_type == AVMEDIA_TYPE_AUDIO) {
1135
+ sample_format = optional_string_to_tensor(to_optional_string(
1136
+ av_get_sample_fmt_name(static_cast<AVSampleFormat>(codecpar.format))));
1137
+ sample_rate = unless_default(codecpar.sample_rate);
1138
+ channel_layout =
1139
+ optional_string_to_tensor(get_channel_layout_name(codecpar));
1140
+ block_align = unless_default(codecpar.block_align);
1141
+ frame_size = unless_default(codecpar.frame_size);
1142
+ initial_padding = unless_default(codecpar.initial_padding);
1143
+ trailing_padding = unless_default(codecpar.trailing_padding);
1144
+ seek_preroll = unless_default(codecpar.seek_preroll);
1145
+ }
1146
+ if (params.container_format != nullptr) {
1147
+ container_format = string_to_tensor(params.container_format->name);
1148
+ }
1149
+ return output;
1150
+ }
1151
+
1152
+ namespace {
1153
+ AVRational to_rational(const char* field, const std::vector<int64_t>& value) {
1154
+ STD_TORCH_CHECK(
1155
+ value.size() == 2,
1156
+ field,
1157
+ " must be [num, den], got ",
1158
+ value.size(),
1159
+ " values.");
1160
+ return {
1161
+ validate_int64_to_int(value[0], field),
1162
+ validate_int64_to_int(value[1], field)};
1163
+ }
1164
+
1165
+ // FFmpeg's *_from_name() functions return a negative value for unknown names.
1166
+ template <typename Enum>
1167
+ Enum checked_enum(const char* field, const std::string& name, int value) {
1168
+ STD_TORCH_CHECK(value >= 0, "Unknown ", field, ": ", name, ".");
1169
+ return static_cast<Enum>(value);
1170
+ }
1171
+
1172
+ void check_bytes(const char* field, const torch::stable::Tensor& tensor) {
1173
+ STD_TORCH_CHECK(
1174
+ tensor.scalar_type() == kStableUInt8 && tensor.dim() == 1 &&
1175
+ tensor.is_contiguous() && tensor.device().type() == kStableCPU,
1176
+ field,
1177
+ " must be a contiguous 1D uint8 CPU tensor.");
1178
+ }
1179
+ } // namespace
1180
+
1181
+ torch::stable::Tensor _blocks_create_packet_decoder(
1182
+ std::string media_type,
1183
+ std::string codec,
1184
+ std::vector<int64_t> time_base,
1185
+ std::optional<torch::stable::Tensor> extradata,
1186
+ std::optional<int64_t> codec_tag,
1187
+ std::optional<int64_t> profile,
1188
+ std::optional<int64_t> level,
1189
+ std::optional<int64_t> bit_rate,
1190
+ std::optional<int64_t> bits_per_coded_sample,
1191
+ std::optional<int64_t> bits_per_raw_sample,
1192
+ std::optional<std::vector<std::string>> coded_side_data_names,
1193
+ std::optional<std::vector<torch::stable::Tensor>> coded_side_data_values,
1194
+ std::optional<int64_t> width,
1195
+ std::optional<int64_t> height,
1196
+ std::optional<std::string> pixel_format,
1197
+ std::optional<std::vector<int64_t>> sample_aspect_ratio,
1198
+ std::optional<std::vector<int64_t>> framerate,
1199
+ std::optional<std::vector<int64_t>> r_frame_rate,
1200
+ std::optional<std::string> field_order,
1201
+ std::optional<std::string> color_range,
1202
+ std::optional<std::string> color_primaries,
1203
+ std::optional<std::string> color_transfer_characteristic,
1204
+ std::optional<std::string> color_space,
1205
+ std::optional<std::string> chroma_location,
1206
+ std::optional<int64_t> video_delay,
1207
+ std::optional<std::string> sample_format,
1208
+ std::optional<int64_t> sample_rate,
1209
+ std::optional<std::string> channel_layout,
1210
+ std::optional<int64_t> block_align,
1211
+ std::optional<int64_t> frame_size,
1212
+ std::optional<int64_t> initial_padding,
1213
+ std::optional<int64_t> trailing_padding,
1214
+ std::optional<int64_t> seek_preroll,
1215
+ std::optional<std::string> container_format,
1216
+ std::optional<int64_t> num_threads,
1217
+ std::string device) {
1218
+ validate_device_interface(device);
1219
+
1220
+ CodecParameters params;
1221
+ AVCodecParameters& codecpar = *params.codecpar;
1222
+
1223
+ const AVCodecDescriptor* descriptor =
1224
+ avcodec_descriptor_get_by_name(codec.c_str());
1225
+ STD_TORCH_CHECK(descriptor != nullptr, "Unknown codec: ", codec, ".");
1226
+ AVMediaType expected_type = parse_media_type(media_type);
1227
+ STD_TORCH_CHECK(
1228
+ descriptor->type == expected_type,
1229
+ "'",
1230
+ codec,
1231
+ "' is not a ",
1232
+ media_type,
1233
+ " codec.");
1234
+ codecpar.codec_type = descriptor->type;
1235
+ codecpar.codec_id = descriptor->id;
1236
+ params.time_base = to_rational("time_base", time_base);
1237
+
1238
+ if (extradata.has_value()) {
1239
+ check_bytes("extradata", *extradata);
1240
+ int size = validate_int64_to_int(extradata->numel(), "extradata size");
1241
+ // Zeroed padding past the end, which FFmpeg's parsers read into.
1242
+ codecpar.extradata = static_cast<uint8_t*>(
1243
+ av_mallocz(static_cast<size_t>(size) + AV_INPUT_BUFFER_PADDING_SIZE));
1244
+ STD_TORCH_CHECK(
1245
+ codecpar.extradata != nullptr, "Failed to allocate the extradata.");
1246
+ std::memcpy(codecpar.extradata, extradata->const_data_ptr<uint8_t>(), size);
1247
+ codecpar.extradata_size = size;
1248
+ }
1249
+ if (codec_tag.has_value()) {
1250
+ codecpar.codec_tag = validate_int64_to_uint32(*codec_tag, "codec_tag");
1251
+ }
1252
+ if (profile.has_value()) {
1253
+ codecpar.profile = validate_int64_to_int(*profile, "profile");
1254
+ }
1255
+ if (level.has_value()) {
1256
+ codecpar.level = validate_int64_to_int(*level, "level");
1257
+ }
1258
+ if (bit_rate.has_value()) {
1259
+ codecpar.bit_rate = *bit_rate;
1260
+ }
1261
+ if (bits_per_coded_sample.has_value()) {
1262
+ codecpar.bits_per_coded_sample =
1263
+ validate_int64_to_int(*bits_per_coded_sample, "bits_per_coded_sample");
1264
+ }
1265
+ if (bits_per_raw_sample.has_value()) {
1266
+ codecpar.bits_per_raw_sample =
1267
+ validate_int64_to_int(*bits_per_raw_sample, "bits_per_raw_sample");
1268
+ }
1269
+ if (coded_side_data_names.has_value()) {
1270
+ STD_TORCH_CHECK(
1271
+ coded_side_data_values.has_value() &&
1272
+ coded_side_data_values->size() == coded_side_data_names->size(),
1273
+ "coded_side_data_names and coded_side_data_values must have the same "
1274
+ "length.");
1275
+ for (size_t i = 0; i < coded_side_data_names->size(); ++i) {
1276
+ const torch::stable::Tensor& value = (*coded_side_data_values)[i];
1277
+ check_bytes("coded_side_data values", value);
1278
+ params.add_stream_side_data(
1279
+ get_packet_side_data_type_from_name((*coded_side_data_names)[i]),
1280
+ value.const_data_ptr<uint8_t>(),
1281
+ value.numel());
1282
+ }
1283
+ }
1284
+
1285
+ if (width.has_value()) {
1286
+ codecpar.width = validate_int64_to_int(*width, "width");
1287
+ }
1288
+ if (height.has_value()) {
1289
+ codecpar.height = validate_int64_to_int(*height, "height");
1290
+ }
1291
+ if (pixel_format.has_value()) {
1292
+ codecpar.format = checked_enum<AVPixelFormat>(
1293
+ "pixel_format", *pixel_format, av_get_pix_fmt(pixel_format->c_str()));
1294
+ }
1295
+ if (sample_aspect_ratio.has_value()) {
1296
+ codecpar.sample_aspect_ratio =
1297
+ to_rational("sample_aspect_ratio", *sample_aspect_ratio);
1298
+ }
1299
+ if (framerate.has_value()) {
1300
+ set_framerate(codecpar, to_rational("framerate", *framerate));
1301
+ }
1302
+ if (r_frame_rate.has_value()) {
1303
+ params.r_frame_rate = to_rational("r_frame_rate", *r_frame_rate);
1304
+ }
1305
+ if (field_order.has_value()) {
1306
+ codecpar.field_order = get_field_order_from_name(*field_order);
1307
+ }
1308
+ if (color_range.has_value()) {
1309
+ codecpar.color_range = checked_enum<AVColorRange>(
1310
+ "color_range",
1311
+ *color_range,
1312
+ av_color_range_from_name(color_range->c_str()));
1313
+ }
1314
+ if (color_primaries.has_value()) {
1315
+ codecpar.color_primaries = checked_enum<AVColorPrimaries>(
1316
+ "color_primaries",
1317
+ *color_primaries,
1318
+ av_color_primaries_from_name(color_primaries->c_str()));
1319
+ }
1320
+ if (color_transfer_characteristic.has_value()) {
1321
+ codecpar.color_trc = checked_enum<AVColorTransferCharacteristic>(
1322
+ "color_transfer_characteristic",
1323
+ *color_transfer_characteristic,
1324
+ av_color_transfer_from_name(color_transfer_characteristic->c_str()));
1325
+ }
1326
+ if (color_space.has_value()) {
1327
+ codecpar.color_space = checked_enum<AVColorSpace>(
1328
+ "color_space",
1329
+ *color_space,
1330
+ av_color_space_from_name(color_space->c_str()));
1331
+ }
1332
+ if (chroma_location.has_value()) {
1333
+ codecpar.chroma_location = checked_enum<AVChromaLocation>(
1334
+ "chroma_location",
1335
+ *chroma_location,
1336
+ av_chroma_location_from_name(chroma_location->c_str()));
1337
+ }
1338
+ if (video_delay.has_value()) {
1339
+ codecpar.video_delay = validate_int64_to_int(*video_delay, "video_delay");
1340
+ }
1341
+
1342
+ if (sample_format.has_value()) {
1343
+ codecpar.format = checked_enum<AVSampleFormat>(
1344
+ "sample_format",
1345
+ *sample_format,
1346
+ av_get_sample_fmt(sample_format->c_str()));
1347
+ }
1348
+ if (sample_rate.has_value()) {
1349
+ codecpar.sample_rate = validate_int64_to_int(*sample_rate, "sample_rate");
1350
+ }
1351
+ if (channel_layout.has_value()) {
1352
+ set_channel_layout(codecpar, *channel_layout);
1353
+ }
1354
+ if (block_align.has_value()) {
1355
+ codecpar.block_align = validate_int64_to_int(*block_align, "block_align");
1356
+ }
1357
+ if (frame_size.has_value()) {
1358
+ codecpar.frame_size = validate_int64_to_int(*frame_size, "frame_size");
1359
+ }
1360
+ if (initial_padding.has_value()) {
1361
+ codecpar.initial_padding =
1362
+ validate_int64_to_int(*initial_padding, "initial_padding");
1363
+ }
1364
+ if (trailing_padding.has_value()) {
1365
+ codecpar.trailing_padding =
1366
+ validate_int64_to_int(*trailing_padding, "trailing_padding");
1367
+ }
1368
+ if (seek_preroll.has_value()) {
1369
+ codecpar.seek_preroll =
1370
+ validate_int64_to_int(*seek_preroll, "seek_preroll");
1371
+ }
1372
+
1373
+ if (container_format.has_value()) {
1374
+ params.container_format = av_find_input_format(container_format->c_str());
1375
+ STD_TORCH_CHECK(
1376
+ params.container_format != nullptr,
1377
+ "Unknown container_format: ",
1378
+ *container_format,
1379
+ ".");
1380
+ }
1381
+
1382
+ auto decoder = std::make_unique<PacketDecoder>(
1383
+ params,
1384
+ StableDevice(device),
1385
+ validate_optional_int64_to_int(num_threads, "num_threads"));
1386
+ return wrap_pointer_to_tensor<PacketDecoder>(std::move(decoder));
1387
+ }
1388
+
1389
+ torch::stable::Tensor _blocks_create_packet(
1390
+ const torch::stable::Tensor& data,
1391
+ std::optional<int64_t> pts,
1392
+ std::optional<int64_t> dts,
1393
+ int64_t duration,
1394
+ int64_t flags,
1395
+ std::optional<std::vector<std::string>> side_data_names,
1396
+ std::optional<std::vector<torch::stable::Tensor>> side_data_values) {
1397
+ check_bytes("data", data);
1398
+ int size = validate_int64_to_int(data.numel(), "data size");
1399
+ int packet_flags = validate_int64_to_int(flags, "flags");
1400
+ // It tells FFmpeg that the data can be trusted to hold pointers, which some
1401
+ // decoders then follow.
1402
+ STD_TORCH_CHECK(
1403
+ (packet_flags & AV_PKT_FLAG_TRUSTED) == 0,
1404
+ "flags must not contain AV_PKT_FLAG_TRUSTED.");
1405
+
1406
+ UniqueAVPacket packet(av_packet_alloc());
1407
+ STD_TORCH_CHECK(packet != nullptr, "Failed to allocate the packet.");
1408
+ // av_new_packet() also allocates the zeroed padding past the end of the
1409
+ // data, which decoders read into.
1410
+ int status = av_new_packet(packet.get(), size);
1411
+ STD_TORCH_CHECK(
1412
+ status == AVSUCCESS,
1413
+ "Failed to allocate the packet data: ",
1414
+ get_ffmpeg_error_string_from_error_code(status));
1415
+ if (size > 0) {
1416
+ std::memcpy(packet->data, data.const_data_ptr<uint8_t>(), size);
1417
+ }
1418
+ packet->pts = pts.value_or(AV_NOPTS_VALUE);
1419
+ packet->dts = dts.value_or(AV_NOPTS_VALUE);
1420
+ packet->duration = duration;
1421
+ packet->flags = packet_flags;
1422
+
1423
+ if (side_data_names.has_value()) {
1424
+ STD_TORCH_CHECK(
1425
+ side_data_values.has_value() &&
1426
+ side_data_values->size() == side_data_names->size(),
1427
+ "side_data_names and side_data_values must have the same length.");
1428
+ for (size_t i = 0; i < side_data_names->size(); ++i) {
1429
+ const torch::stable::Tensor& value = (*side_data_values)[i];
1430
+ check_bytes("side_data values", value);
1431
+ int value_size =
1432
+ validate_int64_to_int(value.numel(), "side_data value size");
1433
+ uint8_t* destination = av_packet_new_side_data(
1434
+ packet.get(),
1435
+ get_packet_side_data_type_from_name((*side_data_names)[i]),
1436
+ value_size);
1437
+ STD_TORCH_CHECK(
1438
+ destination != nullptr, "Failed to allocate the side data.");
1439
+ if (value_size > 0) {
1440
+ std::memcpy(destination, value.const_data_ptr<uint8_t>(), value_size);
1441
+ }
1442
+ }
1443
+ }
1444
+ return wrap_pointer_to_tensor(std::move(packet));
1445
+ }
1446
+
1447
+ using OpsPacketFieldsOutput = std::tuple<
1448
+ torch::stable::Tensor, // data
1449
+ std::optional<int64_t>, // pts
1450
+ std::optional<int64_t>, // dts
1451
+ int64_t, // duration
1452
+ int64_t, // flags
1453
+ // See Note [Returning text from ops].
1454
+ std::vector<int64_t>, // side_data_types
1455
+ std::vector<torch::stable::Tensor>>; // side_data_values
1456
+
1457
+ OpsPacketFieldsOutput _blocks_packet_get_fields(torch::stable::Tensor& packet) {
1458
+ const AVPacket* av_packet = unwrap_tensor_to_pointer<AVPacket>(packet);
1459
+
1460
+ OpsPacketFieldsOutput output;
1461
+ auto& [data, pts, dts, duration, flags, side_data_types, side_data_values] =
1462
+ output;
1463
+ if (av_packet->size == 0) {
1464
+ data = torch::stable::empty({int64_t(0)}, kStableUInt8);
1465
+ } else {
1466
+ // A view on the packet's data. As for the frame planes, the deleter
1467
+ // captures a copy of the packet handle, which keeps the packet alive as
1468
+ // long as the view is (see test_packet_data_outlives_packet).
1469
+ torch::stable::Tensor handle_copy = packet;
1470
+ int64_t sizes[] = {av_packet->size};
1471
+ int64_t strides[] = {1};
1472
+ data = torch::stable::from_blob(
1473
+ av_packet->data,
1474
+ {sizes, 1},
1475
+ {strides, 1},
1476
+ StableDevice(kStableCPU),
1477
+ kStableUInt8,
1478
+ [handle_copy](void*) {});
1479
+ }
1480
+ if (av_packet->pts != AV_NOPTS_VALUE) {
1481
+ pts = av_packet->pts;
1482
+ }
1483
+ if (av_packet->dts != AV_NOPTS_VALUE) {
1484
+ dts = av_packet->dts;
1485
+ }
1486
+ duration = av_packet->duration;
1487
+ flags = av_packet->flags;
1488
+ for (int i = 0; i < av_packet->side_data_elems; ++i) {
1489
+ const AVPacketSideData& side_data = av_packet->side_data[i];
1490
+ // A type this FFmpeg can't name is a type it doesn't know what to do with
1491
+ // either, so there's nothing a decoder would read from it.
1492
+ if (av_packet_side_data_name(side_data.type) != nullptr) {
1493
+ side_data_types.push_back(static_cast<int64_t>(side_data.type));
1494
+ side_data_values.push_back(
1495
+ bytes_to_tensor(side_data.data, side_data.size));
1496
+ }
1497
+ }
1498
+ return output;
1499
+ }
1500
+
1501
+ int64_t _blocks_packet_decoder_send_packet(
1502
+ torch::stable::Tensor& decoder,
1503
+ torch::stable::Tensor& packet) {
1504
+ PacketDecoder* decoder_ptr = unwrap_tensor_to_pointer<PacketDecoder>(decoder);
1505
+ return static_cast<int64_t>(
1506
+ decoder_ptr->send_packet(*unwrap_tensor_to_pointer<AVPacket>(packet)));
1507
+ }
1508
+
1509
+ int64_t _blocks_packet_decoder_send_eof(torch::stable::Tensor& decoder) {
1510
+ PacketDecoder* decoder_ptr = unwrap_tensor_to_pointer<PacketDecoder>(decoder);
1511
+ return static_cast<int64_t>(decoder_ptr->send_eof());
1512
+ }
1513
+
1514
+ void _blocks_packet_decoder_reset(torch::stable::Tensor& decoder) {
1515
+ unwrap_tensor_to_pointer<PacketDecoder>(decoder)->reset();
1516
+ }
1517
+
1518
+ // (frame_handle, status, pts, pts_seconds, duration_seconds, storage). `pts`
1519
+ // is in the decoder's time base, and is None when the frame has no timestamp.
1520
+ using OpsReceiveFrameOutput = std::tuple<
1521
+ torch::stable::Tensor,
1522
+ int64_t,
1523
+ std::optional<int64_t>,
1524
+ double,
1525
+ double,
1526
+ torch::stable::Tensor>;
1527
+
1528
+ namespace {
1529
+ std::optional<int64_t> to_optional_pts(int64_t pts) {
1530
+ if (pts == AV_NOPTS_VALUE) {
1531
+ return std::nullopt;
1532
+ }
1533
+ return pts;
1534
+ }
1535
+
1536
+ double pts_to_seconds_or_nan(int64_t pts, const AVRational& time_base) {
1537
+ return pts == INT64_MIN ? std::numeric_limits<double>::quiet_NaN()
1538
+ : pts_to_seconds(pts, time_base);
1539
+ }
1540
+ } // namespace
1541
+
1542
+ OpsReceiveFrameOutput _blocks_packet_decoder_receive_frame(
1543
+ torch::stable::Tensor& decoder) {
1544
+ PacketDecoder* decoder_ptr = unwrap_tensor_to_pointer<PacketDecoder>(decoder);
1545
+ UniqueAVFrame av_frame(av_frame_alloc());
1546
+ STD_TORCH_CHECK(av_frame != nullptr, "Failed to allocate AVFrame");
1547
+ int status = decoder_ptr->receive_frame(av_frame);
1548
+ if (status != AVSUCCESS) {
1549
+ return std::make_tuple(
1550
+ torch::stable::full({1}, 0, kStableInt64),
1551
+ static_cast<int64_t>(status),
1552
+ std::nullopt,
1553
+ 0.0,
1554
+ 0.0,
1555
+ torch::stable::empty({int64_t(0)}, kStableUInt8));
1556
+ }
1557
+ AVRational time_base = decoder_ptr->time_base();
1558
+ int64_t pts = get_pts_or_dts(*av_frame);
1559
+ double pts_seconds = pts_to_seconds_or_nan(pts, time_base);
1560
+ double duration_seconds = pts_to_seconds(get_duration(*av_frame), time_base);
1561
+ torch::stable::Tensor storage =
1562
+ decoder_ptr->get_frame_storage(*av_frame).value_or(
1563
+ torch::stable::empty({int64_t(0)}, kStableUInt8));
1564
+ return std::make_tuple(
1565
+ wrap_pointer_to_tensor(std::move(av_frame)),
1566
+ static_cast<int64_t>(0),
1567
+ to_optional_pts(pts),
1568
+ pts_seconds,
1569
+ duration_seconds,
1570
+ storage);
1571
+ }
1572
+
1573
+ // (samples, status, pts, pts_seconds, duration_seconds, sample_rate).
1574
+ // `samples` is [num_channels, num_samples] in the frame's own sample type;
1575
+ // there is no frame handle because, unlike a video frame, nothing downstream
1576
+ // needs the AVFrame itself. `pts` is as for video frames.
1577
+ using OpsReceiveAudioFrameOutput = std::tuple<
1578
+ torch::stable::Tensor,
1579
+ int64_t,
1580
+ std::optional<int64_t>,
1581
+ double,
1582
+ double,
1583
+ int64_t>;
1584
+
1585
+ OpsReceiveAudioFrameOutput _blocks_audio_packet_decoder_receive_frame(
1586
+ torch::stable::Tensor& decoder) {
1587
+ PacketDecoder* decoder_ptr = unwrap_tensor_to_pointer<PacketDecoder>(decoder);
1588
+ STD_TORCH_CHECK(
1589
+ decoder_ptr->media_type() == AVMEDIA_TYPE_AUDIO,
1590
+ "This PacketDecoder decodes video, not audio.");
1591
+
1592
+ UniqueAVFrame av_frame(av_frame_alloc());
1593
+ STD_TORCH_CHECK(av_frame != nullptr, "Failed to allocate AVFrame");
1594
+ int status = decoder_ptr->receive_frame(av_frame);
1595
+ if (status != AVSUCCESS) {
1596
+ return std::make_tuple(
1597
+ torch::stable::empty({int64_t(0)}, kStableUInt8),
1598
+ static_cast<int64_t>(status),
1599
+ std::nullopt,
1600
+ 0.0,
1601
+ 0.0,
1602
+ static_cast<int64_t>(0));
1603
+ }
1604
+
1605
+ AVRational time_base = decoder_ptr->time_base();
1606
+ int64_t pts = get_pts_or_dts(*av_frame);
1607
+ return std::make_tuple(
1608
+ get_audio_samples(*av_frame),
1609
+ static_cast<int64_t>(0),
1610
+ to_optional_pts(pts),
1611
+ pts_to_seconds_or_nan(pts, time_base),
1612
+ pts_to_seconds(get_duration(*av_frame), time_base),
1613
+ static_cast<int64_t>(av_frame->sample_rate));
1614
+ }
1615
+
1616
+ torch::stable::Tensor _blocks_create_color_converter(
1617
+ std::string device,
1618
+ std::string output_dtype) {
1619
+ validate_device_interface(device);
1620
+ auto converter = std::make_unique<ColorConverter>(
1621
+ StableDevice(device), parse_output_dtype_config(output_dtype));
1622
+ return wrap_pointer_to_tensor<ColorConverter>(std::move(converter));
1623
+ }
1624
+
1625
+ torch::stable::Tensor _blocks_convert_frame(
1626
+ torch::stable::Tensor& converter,
1627
+ torch::stable::Tensor& frame,
1628
+ StableDevice device) {
1629
+ ColorConverter* converter_ptr =
1630
+ unwrap_tensor_to_pointer<ColorConverter>(converter);
1631
+ return converter_ptr->convert(
1632
+ *unwrap_tensor_to_pointer<AVFrame>(frame), device);
1633
+ }
1634
+
1635
+ torch::stable::Tensor _blocks_create_audio_converter(
1636
+ std::optional<int64_t> sample_rate,
1637
+ std::optional<int64_t> num_channels) {
1638
+ auto converter = std::make_unique<AudioConverter>(
1639
+ to_optional_int(sample_rate), to_optional_int(num_channels));
1640
+ return wrap_pointer_to_tensor<AudioConverter>(std::move(converter));
1641
+ }
1642
+
1643
+ torch::stable::Tensor _blocks_audio_converter_convert(
1644
+ torch::stable::Tensor& converter,
1645
+ const torch::stable::Tensor& samples,
1646
+ int64_t sample_rate) {
1647
+ return unwrap_tensor_to_pointer<AudioConverter>(converter)->convert(
1648
+ samples, static_cast<int>(sample_rate));
1649
+ }
1650
+
1651
+ torch::stable::Tensor _blocks_audio_converter_drain(
1652
+ torch::stable::Tensor& converter) {
1653
+ return unwrap_tensor_to_pointer<AudioConverter>(converter)->drain();
1654
+ }
1655
+
1656
+ void _blocks_audio_converter_reset(torch::stable::Tensor& converter) {
1657
+ unwrap_tensor_to_pointer<AudioConverter>(converter)->reset();
1658
+ }
1659
+
1660
+ // The enum fields are returned as FFmpeg's raw values, see
1661
+ // Note [Returning text from ops].
1662
+ using OpsFrameMetadataOutput = std::tuple<
1663
+ int64_t, // pixel format
1664
+ int64_t, // color space
1665
+ int64_t, // color range
1666
+ int64_t, // color primaries
1667
+ int64_t, // color transfer characteristic
1668
+ int64_t, // bit depth
1669
+ int64_t, // width
1670
+ int64_t, // height
1671
+ double>; // rotation, in degrees
1672
+
1673
+ OpsFrameMetadataOutput _blocks_frame_metadata(
1674
+ torch::stable::Tensor& tensor_handle) {
1675
+ FrameMetadata metadata =
1676
+ get_frame_metadata(*unwrap_tensor_to_pointer<AVFrame>(tensor_handle));
1677
+ return std::make_tuple(
1678
+ static_cast<int64_t>(metadata.pixel_format),
1679
+ static_cast<int64_t>(metadata.color_space),
1680
+ static_cast<int64_t>(metadata.color_range),
1681
+ static_cast<int64_t>(metadata.color_primaries),
1682
+ static_cast<int64_t>(metadata.color_transfer_characteristic),
1683
+ metadata.bit_depth,
1684
+ metadata.width,
1685
+ metadata.height,
1686
+ metadata.rotation);
1687
+ }
1688
+
1689
+ // Must match _FFmpegEnum in decoders/_blocks/_frame.py.
1690
+ enum class FFmpegEnum : int64_t {
1691
+ PixelFormat = 0,
1692
+ ColorSpace = 1,
1693
+ ColorRange = 2,
1694
+ ColorPrimaries = 3,
1695
+ ColorTransferCharacteristic = 4,
1696
+ PacketSideDataType = 5,
1697
+ };
1698
+
1699
+ // The name FFmpeg gives to `value` of the enum `kind`. See
1700
+ // Note [Returning text from ops].
1701
+ std::string _blocks_get_ffmpeg_enum_name(int64_t kind, int64_t value) {
1702
+ const char* name = nullptr;
1703
+ switch (static_cast<FFmpegEnum>(kind)) {
1704
+ case FFmpegEnum::PixelFormat:
1705
+ name = av_get_pix_fmt_name(static_cast<AVPixelFormat>(value));
1706
+ break;
1707
+ case FFmpegEnum::ColorSpace:
1708
+ name = av_color_space_name(static_cast<AVColorSpace>(value));
1709
+ break;
1710
+ case FFmpegEnum::ColorRange:
1711
+ name = av_color_range_name(static_cast<AVColorRange>(value));
1712
+ break;
1713
+ case FFmpegEnum::ColorPrimaries:
1714
+ name = av_color_primaries_name(static_cast<AVColorPrimaries>(value));
1715
+ break;
1716
+ case FFmpegEnum::ColorTransferCharacteristic:
1717
+ name = av_color_transfer_name(
1718
+ static_cast<AVColorTransferCharacteristic>(value));
1719
+ break;
1720
+ case FFmpegEnum::PacketSideDataType:
1721
+ name = av_packet_side_data_name(static_cast<AVPacketSideDataType>(value));
1722
+ break;
1723
+ default:
1724
+ STD_TORCH_CHECK(false, "Unknown FFmpeg enum kind: ", kind);
1725
+ }
1726
+ return name != nullptr ? name : "unknown";
1727
+ }
1728
+
1729
+ using OpsFramePlanesOutput = std::tuple<
1730
+ torch::stable::Tensor,
1731
+ torch::stable::Tensor,
1732
+ torch::stable::Tensor,
1733
+ torch::stable::Tensor>;
1734
+
1735
+ OpsFramePlanesOutput _blocks_frame_planes(
1736
+ torch::stable::Tensor& tensor_handle,
1737
+ StableDevice device) {
1738
+ AVFrame* av_frame = unwrap_tensor_to_pointer<AVFrame>(tensor_handle);
1739
+ std::vector<torch::stable::Tensor> planes =
1740
+ get_frame_planes(*av_frame, device, tensor_handle);
1741
+
1742
+ // Op schema wants a fixed number of planes, so we pad with empty tensors that
1743
+ // then get removed at the Python level.
1744
+ planes.resize(4, torch::stable::empty({int64_t(0)}, kStableUInt8));
1745
+ return std::make_tuple(planes[0], planes[1], planes[2], planes[3]);
1746
+ }
1747
+
1748
+ // For testing only. We need to implement this operation as a core library
1749
+ // function because what we're testing is round-tripping pts values as
1750
+ // double-precision floating point numbers from C++ to Python and back to C++.
1751
+ // We want to make sure that the value is preserved exactly, bit-for-bit, during
1752
+ // this process.
1753
+ //
1754
+ // Returns true if for the given decoder, the pts
1755
+ // value when converted to seconds as a double is exactly pts_seconds_to_test.
1756
+ // Returns false otherwise.
1757
+ bool _test_frame_pts_equality(
1758
+ torch::stable::Tensor& decoder,
1759
+ int64_t frame_index,
1760
+ double pts_seconds_to_test) {
1761
+ auto video_decoder = unwrap_tensor_to_get_decoder(decoder);
1762
+ return pts_seconds_to_test ==
1763
+ video_decoder->get_pts_seconds_for_frame(frame_index);
1764
+ }
1765
+
1766
+ torch::stable::Tensor _get_key_frame_indices(torch::stable::Tensor& decoder) {
1767
+ auto video_decoder = unwrap_tensor_to_get_decoder(decoder);
1768
+ return video_decoder->get_key_frame_indices();
1769
+ }
1770
+
1771
+ // Get the metadata from the video as a string.
1772
+ std::string get_json_metadata(torch::stable::Tensor& decoder) {
1773
+ auto video_decoder = unwrap_tensor_to_get_decoder(decoder);
1774
+
1775
+ ContainerMetadata video_metadata = video_decoder->get_container_metadata();
1776
+ auto maybe_best_video_stream_index = video_metadata.best_video_stream_index;
1777
+
1778
+ std::map<std::string, std::string> metadata_map;
1779
+ // serialize the metadata into a string std::stringstream ss;
1780
+ double duration_seconds_from_header = 0;
1781
+ if (maybe_best_video_stream_index.has_value() &&
1782
+ video_metadata.all_stream_metadata[*maybe_best_video_stream_index]
1783
+ .duration_seconds_from_header.has_value()) {
1784
+ duration_seconds_from_header =
1785
+ video_metadata.all_stream_metadata[*maybe_best_video_stream_index]
1786
+ .duration_seconds_from_header.value_or(0);
1787
+ } else {
1788
+ // Fallback to container-level duration if stream duration is not found.
1789
+ duration_seconds_from_header =
1790
+ video_metadata.duration_seconds_from_header.value_or(0);
1791
+ }
1792
+ metadata_map["durationSecondsFromHeader"] =
1793
+ fmt::to_string(duration_seconds_from_header);
1794
+
1795
+ if (video_metadata.bit_rate.has_value()) {
1796
+ metadata_map["bitRate"] = fmt::to_string(video_metadata.bit_rate.value());
1797
+ }
1798
+
1799
+ if (maybe_best_video_stream_index.has_value()) {
1800
+ auto stream_metadata =
1801
+ video_metadata.all_stream_metadata[*maybe_best_video_stream_index];
1802
+ if (stream_metadata.num_frames_from_content.has_value()) {
1803
+ metadata_map["numFramesFromHeader"] =
1804
+ std::to_string(*stream_metadata.num_frames_from_content);
1805
+ } else if (stream_metadata.num_frames_from_header.has_value()) {
1806
+ metadata_map["numFramesFromHeader"] =
1807
+ std::to_string(*stream_metadata.num_frames_from_header);
1808
+ }
1809
+ if (stream_metadata.begin_stream_pts_seconds_from_content.has_value()) {
1810
+ metadata_map["beginStreamSecondsFromContent"] = fmt::to_string(
1811
+ *stream_metadata.begin_stream_pts_seconds_from_content);
1812
+ }
1813
+ if (stream_metadata.end_stream_pts_seconds_from_content.has_value()) {
1814
+ metadata_map["endStreamSecondsFromContent"] =
1815
+ fmt::to_string(*stream_metadata.end_stream_pts_seconds_from_content);
1816
+ }
1817
+ if (stream_metadata.codec_name.has_value()) {
1818
+ metadata_map["codec"] = quote_value(stream_metadata.codec_name.value());
1819
+ }
1820
+ if (stream_metadata.post_rotation_width.has_value()) {
1821
+ metadata_map["width"] =
1822
+ std::to_string(*stream_metadata.post_rotation_width);
1823
+ }
1824
+ if (stream_metadata.post_rotation_height.has_value()) {
1825
+ metadata_map["height"] =
1826
+ std::to_string(*stream_metadata.post_rotation_height);
1827
+ }
1828
+ if (stream_metadata.average_fps_from_header.has_value()) {
1829
+ metadata_map["averageFpsFromHeader"] =
1830
+ fmt::to_string(*stream_metadata.average_fps_from_header);
1831
+ }
1832
+ }
1833
+ if (video_metadata.best_video_stream_index.has_value()) {
1834
+ metadata_map["bestVideoStreamIndex"] =
1835
+ std::to_string(*video_metadata.best_video_stream_index);
1836
+ }
1837
+ if (video_metadata.best_audio_stream_index.has_value()) {
1838
+ metadata_map["bestAudioStreamIndex"] =
1839
+ std::to_string(*video_metadata.best_audio_stream_index);
1840
+ }
1841
+
1842
+ return map_to_json(metadata_map);
1843
+ }
1844
+
1845
+ // Get the container metadata as a string.
1846
+ namespace {
1847
+ // The half of a stream's metadata that comes from the container header. Shared
1848
+ // by get_stream_json_metadata, which then adds the content-derived and
1849
+ // fallback-computed fields, and by the Demuxer building block, which has only
1850
+ // this half to report.
1851
+ void write_header_based_metadata(
1852
+ std::map<std::string, std::string>& map,
1853
+ const StreamMetadata& stream_metadata) {
1854
+ if (stream_metadata.duration_seconds_from_header.has_value()) {
1855
+ map["durationSecondsFromHeader"] =
1856
+ fmt::to_string(*stream_metadata.duration_seconds_from_header);
1857
+ }
1858
+ if (stream_metadata.bit_rate.has_value()) {
1859
+ map["bitRate"] = fmt::to_string(*stream_metadata.bit_rate);
1860
+ }
1861
+ if (stream_metadata.num_frames_from_header.has_value()) {
1862
+ map["numFramesFromHeader"] =
1863
+ std::to_string(*stream_metadata.num_frames_from_header);
1864
+ }
1865
+ if (stream_metadata.begin_stream_seconds_from_header.has_value()) {
1866
+ map["beginStreamSecondsFromHeader"] =
1867
+ fmt::to_string(*stream_metadata.begin_stream_seconds_from_header);
1868
+ }
1869
+ if (stream_metadata.codec_name.has_value()) {
1870
+ map["codec"] = quote_value(stream_metadata.codec_name.value());
1871
+ }
1872
+ if (stream_metadata.time_base.has_value()) {
1873
+ map["timeBaseNum"] = std::to_string(stream_metadata.time_base->num);
1874
+ map["timeBaseDen"] = std::to_string(stream_metadata.time_base->den);
1875
+ }
1876
+ if (stream_metadata.post_rotation_width.has_value()) {
1877
+ map["width"] = std::to_string(*stream_metadata.post_rotation_width);
1878
+ }
1879
+ if (stream_metadata.post_rotation_height.has_value()) {
1880
+ map["height"] = std::to_string(*stream_metadata.post_rotation_height);
1881
+ }
1882
+ if (stream_metadata.sample_aspect_ratio.has_value()) {
1883
+ map["sampleAspectRatioNum"] =
1884
+ std::to_string((*stream_metadata.sample_aspect_ratio).num);
1885
+ map["sampleAspectRatioDen"] =
1886
+ std::to_string((*stream_metadata.sample_aspect_ratio).den);
1887
+ }
1888
+ if (stream_metadata.rotation.has_value()) {
1889
+ map["rotation"] = std::to_string(*stream_metadata.rotation);
1890
+ }
1891
+ if (auto name = stream_metadata.get_color_primaries_name()) {
1892
+ map["colorPrimaries"] = quote_value(*name);
1893
+ }
1894
+ if (auto name = stream_metadata.get_color_space_name()) {
1895
+ map["colorSpace"] = quote_value(*name);
1896
+ }
1897
+ if (auto name = stream_metadata.get_color_transfer_characteristic_name()) {
1898
+ map["colorTransferCharacteristic"] = quote_value(*name);
1899
+ }
1900
+ if (stream_metadata.pixel_format.has_value()) {
1901
+ map["pixelFormat"] = quote_value(stream_metadata.pixel_format.value());
1902
+ }
1903
+ if (stream_metadata.average_fps_from_header.has_value()) {
1904
+ map["averageFpsFromHeader"] =
1905
+ fmt::to_string(*stream_metadata.average_fps_from_header);
1906
+ }
1907
+ if (stream_metadata.sample_rate.has_value()) {
1908
+ map["sampleRate"] = std::to_string(*stream_metadata.sample_rate);
1909
+ }
1910
+ if (stream_metadata.num_channels.has_value()) {
1911
+ map["numChannels"] = std::to_string(*stream_metadata.num_channels);
1912
+ }
1913
+ if (stream_metadata.sample_format.has_value()) {
1914
+ map["sampleFormat"] = quote_value(stream_metadata.sample_format.value());
1915
+ }
1916
+ // "video", "audio", "subtitle", "data" or "attachment".
1917
+ const char* media_type_name =
1918
+ av_get_media_type_string(stream_metadata.media_type);
1919
+ map["mediaType"] =
1920
+ quote_value(media_type_name == nullptr ? "unknown" : media_type_name);
1921
+ }
1922
+ } // namespace
1923
+
1924
+ // The container header, as the Demuxer building block reports it: container
1925
+ // facts plus one entry per stream, and nothing derived from content. The
1926
+ // low-level APIs never merge the two, so a caller always knows which of the
1927
+ // two sources a number came from.
1928
+ torch::stable::Tensor _blocks_demuxer_container_json_metadata(
1929
+ torch::stable::Tensor& demuxer) {
1930
+ ContainerMetadata metadata = get_container_metadata_from_format_context(
1931
+ unwrap_tensor_to_pointer<Demuxer>(demuxer)->format_context().get());
1932
+
1933
+ std::map<std::string, std::string> map;
1934
+ if (metadata.duration_seconds_from_header.has_value()) {
1935
+ map["durationSecondsFromHeader"] =
1936
+ fmt::to_string(*metadata.duration_seconds_from_header);
1937
+ }
1938
+ if (metadata.bit_rate.has_value()) {
1939
+ map["bitRate"] = fmt::to_string(*metadata.bit_rate);
1940
+ }
1941
+ if (metadata.best_video_stream_index.has_value()) {
1942
+ map["bestVideoStreamIndex"] =
1943
+ std::to_string(*metadata.best_video_stream_index);
1944
+ }
1945
+ if (metadata.best_audio_stream_index.has_value()) {
1946
+ map["bestAudioStreamIndex"] =
1947
+ std::to_string(*metadata.best_audio_stream_index);
1948
+ }
1949
+ map["numStreams"] = std::to_string(metadata.all_stream_metadata.size());
1950
+ return map_to_json_tensor(map);
1951
+ }
1952
+
1953
+ torch::stable::Tensor _blocks_demuxer_stream_json_metadata(
1954
+ torch::stable::Tensor& demuxer,
1955
+ int64_t stream_index) {
1956
+ ContainerMetadata metadata = get_container_metadata_from_format_context(
1957
+ unwrap_tensor_to_pointer<Demuxer>(demuxer)->format_context().get());
1958
+ STABLE_CHECK_INDEX(
1959
+ stream_index >= 0 &&
1960
+ stream_index <
1961
+ static_cast<int64_t>(metadata.all_stream_metadata.size()),
1962
+ "stream_index out of bounds: " + std::to_string(stream_index));
1963
+
1964
+ std::map<std::string, std::string> map;
1965
+ write_header_based_metadata(map, metadata.all_stream_metadata[stream_index]);
1966
+ return map_to_json_tensor(map);
1967
+ }
1968
+
1969
+ torch::stable::Tensor get_container_json_metadata(
1970
+ torch::stable::Tensor& decoder) {
1971
+ auto video_decoder = unwrap_tensor_to_get_decoder(decoder);
1972
+
1973
+ auto container_metadata = video_decoder->get_container_metadata();
1974
+
1975
+ std::map<std::string, std::string> map;
1976
+
1977
+ if (container_metadata.duration_seconds_from_header.has_value()) {
1978
+ map["durationSecondsFromHeader"] =
1979
+ fmt::to_string(*container_metadata.duration_seconds_from_header);
1980
+ }
1981
+
1982
+ if (container_metadata.bit_rate.has_value()) {
1983
+ map["bitRate"] = fmt::to_string(*container_metadata.bit_rate);
1984
+ }
1985
+
1986
+ if (container_metadata.best_video_stream_index.has_value()) {
1987
+ map["bestVideoStreamIndex"] =
1988
+ std::to_string(*container_metadata.best_video_stream_index);
1989
+ }
1990
+ if (container_metadata.best_audio_stream_index.has_value()) {
1991
+ map["bestAudioStreamIndex"] =
1992
+ std::to_string(*container_metadata.best_audio_stream_index);
1993
+ }
1994
+
1995
+ map["numStreams"] =
1996
+ std::to_string(container_metadata.all_stream_metadata.size());
1997
+
1998
+ return map_to_json_tensor(map);
1999
+ }
2000
+
2001
+ // Get the stream metadata as JSON.
2002
+ torch::stable::Tensor get_stream_json_metadata(
2003
+ torch::stable::Tensor& decoder,
2004
+ int64_t stream_index) {
2005
+ auto video_decoder = unwrap_tensor_to_get_decoder(decoder);
2006
+ auto all_stream_metadata =
2007
+ video_decoder->get_container_metadata().all_stream_metadata;
2008
+ STABLE_CHECK_INDEX(
2009
+ stream_index >= 0 &&
2010
+ stream_index < static_cast<int64_t>(all_stream_metadata.size()),
2011
+ "stream_index out of bounds: " + std::to_string(stream_index));
2012
+
2013
+ auto stream_metadata = all_stream_metadata[stream_index];
2014
+ auto seek_mode = video_decoder->get_seek_mode();
2015
+ int active_stream_index = video_decoder->get_active_stream_index();
2016
+
2017
+ std::map<std::string, std::string> map;
2018
+
2019
+ write_header_based_metadata(map, stream_metadata);
2020
+ if (stream_metadata.num_frames_from_content.has_value()) {
2021
+ map["numFramesFromContent"] =
2022
+ std::to_string(*stream_metadata.num_frames_from_content);
2023
+ }
2024
+ if (stream_metadata.begin_stream_pts_seconds_from_content.has_value()) {
2025
+ map["beginStreamSecondsFromContent"] =
2026
+ fmt::to_string(*stream_metadata.begin_stream_pts_seconds_from_content);
2027
+ }
2028
+ if (stream_metadata.end_stream_pts_seconds_from_content.has_value()) {
2029
+ map["endStreamSecondsFromContent"] =
2030
+ fmt::to_string(*stream_metadata.end_stream_pts_seconds_from_content);
2031
+ }
2032
+
2033
+ // Check whether content-based metadata is available for this stream.
2034
+ // In exact mode: content-based metadata exists for all streams.
2035
+ // In approximate mode: content-based metadata does not exist for any stream.
2036
+ // In custom_frame_mappings: content-based metadata exists only for the active
2037
+ // stream.
2038
+ //
2039
+ // Our fallback logic assumes content-based metadata is available.
2040
+ // It is available for decoding on the active stream, but would break
2041
+ // when getting metadata from non-active streams.
2042
+ if ((seek_mode != SeekMode::custom_frame_mappings) ||
2043
+ (seek_mode == SeekMode::custom_frame_mappings &&
2044
+ stream_index == active_stream_index)) {
2045
+ write_fallback_based_metadata(map, stream_metadata, seek_mode);
2046
+ } else if (seek_mode == SeekMode::custom_frame_mappings) {
2047
+ // If this is not the active stream, then we don't have content-based
2048
+ // metadata for custom frame mappings. In that case, we want the same
2049
+ // behavior as we would get with approximate mode. Encoding this behavior in
2050
+ // the fallback logic itself is tricky and not worth it for this corner
2051
+ // case. So we hardcode in approximate mode.
2052
+ //
2053
+ // TODO: This hacky behavior is only necessary because the custom frame
2054
+ // mapping is supplied in SingleStreamDecoder::addVideoStream() rather
2055
+ // than in the constructor. And it's supplied to addVideoStream() and
2056
+ // not the constructor because we need to know the stream index. If we
2057
+ // can encode the relevant stream indices into custom frame mappings
2058
+ // itself, then we can put it in the constructor.
2059
+ write_fallback_based_metadata(map, stream_metadata, SeekMode::approximate);
2060
+ }
2061
+
2062
+ return map_to_json_tensor(map);
2063
+ }
2064
+
2065
+ // Returns version information about the various FFMPEG libraries that are
2066
+ // loaded in the program's address space.
2067
+ // TODO: ideally we'd have a more robust way of getting the ffmpeg version,
2068
+ // we're using av_version_info() which is not standardized and shouldn't be
2069
+ // parsed by code (which we do!). See
2070
+ // https://github.com/pytorch/torchcodec/issues/100
2071
+ std::string _get_json_ffmpeg_library_versions() {
2072
+ std::stringstream ss;
2073
+ ss << "{\n";
2074
+
2075
+ unsigned int version = avfilter_version();
2076
+ ss << "\"libavfilter\": [" << AV_VERSION_MAJOR(version) << ", "
2077
+ << AV_VERSION_MINOR(version) << ", " << AV_VERSION_MICRO(version)
2078
+ << "],\n";
2079
+ version = avutil_version();
2080
+ ss << "\"libavutil\": [" << AV_VERSION_MAJOR(version) << ", "
2081
+ << AV_VERSION_MINOR(version) << ", " << AV_VERSION_MICRO(version)
2082
+ << "],\n";
2083
+ version = avcodec_version();
2084
+ ss << "\"libavcodec\": [" << AV_VERSION_MAJOR(version) << ", "
2085
+ << AV_VERSION_MINOR(version) << ", " << AV_VERSION_MICRO(version)
2086
+ << "],\n";
2087
+ version = avformat_version();
2088
+ ss << "\"libavformat\": [" << AV_VERSION_MAJOR(version) << ", "
2089
+ << AV_VERSION_MINOR(version) << ", " << AV_VERSION_MICRO(version)
2090
+ << "],\n";
2091
+ ss << "\"ffmpeg_version\": \"" << av_version_info() << "\"\n";
2092
+ ss << "}\n";
2093
+
2094
+ return ss.str();
2095
+ }
2096
+
2097
+ std::string get_backend_details(torch::stable::Tensor& decoder) {
2098
+ auto video_decoder = unwrap_tensor_to_get_decoder(decoder);
2099
+ return video_decoder->get_device_interface_details();
2100
+ }
2101
+
2102
+ // Scans video packets to get more accurate metadata like frame count, exact
2103
+ // keyframe positions, etc. Exact keyframe positions are useful for efficient
2104
+ // accurate seeking. Note that this function reads the entire video but it does
2105
+ // not decode frames. Reading a video file is much cheaper than decoding it.
2106
+ void scan_all_streams_to_update_metadata(torch::stable::Tensor& decoder) {
2107
+ auto video_decoder = unwrap_tensor_to_get_decoder(decoder);
2108
+ video_decoder->scan_file_and_update_metadata_and_index();
2109
+ }
2110
+
2111
+ torch::stable::Tensor create_streaming_encoder() {
2112
+ auto encoder = std::make_unique<MultiStreamEncoder>();
2113
+ return wrap_multi_stream_encoder_pointer_to_tensor(std::move(encoder));
2114
+ }
2115
+
2116
+ void streaming_encoder_close(torch::stable::Tensor& encoder) {
2117
+ unwrap_tensor_to_get_multi_stream_encoder(encoder)->close();
2118
+ }
2119
+
2120
+ int64_t streaming_encoder_add_video_stream(
2121
+ torch::stable::Tensor& encoder,
2122
+ int64_t height,
2123
+ int64_t width,
2124
+ double frame_rate,
2125
+ std::string device = "cpu",
2126
+ std::optional<std::string> codec = std::nullopt,
2127
+ std::optional<std::string> pixel_format = std::nullopt,
2128
+ std::optional<double> crf = std::nullopt,
2129
+ std::optional<std::string> preset = std::nullopt,
2130
+ std::optional<std::vector<std::string>> extra_options = std::nullopt) {
2131
+ std::optional<std::map<std::string, std::string>> extra_options_map;
2132
+ if (extra_options.has_value()) {
2133
+ extra_options_map = unflatten_extra_options(extra_options.value());
2134
+ }
2135
+ return static_cast<int64_t>(
2136
+ unwrap_tensor_to_get_multi_stream_encoder(encoder)->add_video_stream(
2137
+ static_cast<int>(height),
2138
+ static_cast<int>(width),
2139
+ frame_rate,
2140
+ std::move(device),
2141
+ std::move(codec),
2142
+ std::move(pixel_format),
2143
+ crf,
2144
+ std::move(preset),
2145
+ std::move(extra_options_map)));
2146
+ }
2147
+
2148
+ void streaming_encoder_open_file(
2149
+ torch::stable::Tensor& encoder,
2150
+ std::string filename) {
2151
+ unwrap_tensor_to_get_multi_stream_encoder(encoder)->open(filename);
2152
+ }
2153
+
2154
+ void streaming_encoder_open_file_like(
2155
+ torch::stable::Tensor& encoder,
2156
+ std::string format,
2157
+ int64_t file_like_context) {
2158
+ auto io = adopt_file_like_context(file_like_context);
2159
+ auto avio_context_holder = std::make_unique<AVIOContextHolder>(
2160
+ std::move(io),
2161
+ /*is_for_writing=*/true);
2162
+ unwrap_tensor_to_get_multi_stream_encoder(encoder)->open(
2163
+ format, std::move(avio_context_holder));
2164
+ }
2165
+
2166
+ int64_t streaming_encoder_add_audio_stream(
2167
+ torch::stable::Tensor& encoder,
2168
+ int64_t sample_rate,
2169
+ int64_t num_channels,
2170
+ std::optional<int64_t> bit_rate = std::nullopt,
2171
+ std::optional<int64_t> output_num_channels = std::nullopt,
2172
+ std::optional<int64_t> output_sample_rate = std::nullopt) {
2173
+ return static_cast<int64_t>(
2174
+ unwrap_tensor_to_get_multi_stream_encoder(encoder)->add_audio_stream(
2175
+ validate_int64_to_int(sample_rate, "sample_rate"),
2176
+ validate_int64_to_int(num_channels, "num_channels"),
2177
+ validate_optional_int64_to_int(bit_rate, "bit_rate"),
2178
+ validate_optional_int64_to_int(
2179
+ output_num_channels, "output_num_channels"),
2180
+ validate_optional_int64_to_int(
2181
+ output_sample_rate, "output_sample_rate")));
2182
+ }
2183
+
2184
+ void streaming_encoder_add_frames(
2185
+ torch::stable::Tensor& encoder,
2186
+ const torch::stable::Tensor& frames,
2187
+ int64_t stream_index) {
2188
+ unwrap_tensor_to_get_multi_stream_encoder(encoder)->add_frames(
2189
+ frames, static_cast<int>(stream_index));
2190
+ }
2191
+
2192
+ void streaming_encoder_add_samples(
2193
+ torch::stable::Tensor& encoder,
2194
+ const torch::stable::Tensor& samples,
2195
+ int64_t stream_index) {
2196
+ unwrap_tensor_to_get_multi_stream_encoder(encoder)->add_samples(
2197
+ samples, static_cast<int>(stream_index));
2198
+ }
2199
+
2200
+ torch::stable::Tensor create_wav_decoder_from_file(
2201
+ const std::string& filename) {
2202
+ auto io = std::make_unique<FileIO>(filename, FileIO::Mode::Read);
2203
+ auto decoder = std::make_unique<WavDecoder>(std::move(io));
2204
+ return wrap_wav_decoder_pointer_to_tensor(std::move(decoder));
2205
+ }
2206
+
2207
+ torch::stable::Tensor create_wav_decoder_from_tensor(
2208
+ const torch::stable::Tensor& data) {
2209
+ auto io = std::make_unique<TensorReadIO>(data);
2210
+ auto decoder = std::make_unique<WavDecoder>(std::move(io));
2211
+ return wrap_wav_decoder_pointer_to_tensor(std::move(decoder));
2212
+ }
2213
+
2214
+ torch::stable::Tensor _create_wav_decoder_from_file_like(
2215
+ int64_t file_like_context) {
2216
+ auto io = adopt_file_like_context(file_like_context);
2217
+ auto decoder = std::make_unique<WavDecoder>(std::move(io));
2218
+ return wrap_wav_decoder_pointer_to_tensor(std::move(decoder));
2219
+ }
2220
+
2221
+ OpsAudioFramesOutput get_wav_samples_in_range(
2222
+ torch::stable::Tensor& decoder,
2223
+ double start_seconds,
2224
+ std::optional<double> stop_seconds) {
2225
+ auto wav_decoder = unwrap_tensor_to_get_wav_decoder(decoder);
2226
+ AudioFramesOutput audio_frames =
2227
+ wav_decoder->get_samples_in_range(start_seconds, stop_seconds);
2228
+ return make_ops_audio_frames_output(audio_frames);
2229
+ }
2230
+
2231
+ torch::stable::Tensor get_wav_metadata_from_decoder(
2232
+ torch::stable::Tensor& decoder) {
2233
+ auto wav_decoder = unwrap_tensor_to_get_wav_decoder(decoder);
2234
+ StreamMetadata stream_metadata = wav_decoder->get_stream_metadata();
2235
+
2236
+ std::map<std::string, std::string> metadata_map;
2237
+
2238
+ metadata_map["sampleRate"] = std::to_string(*stream_metadata.sample_rate);
2239
+ metadata_map["numChannels"] = std::to_string(*stream_metadata.num_channels);
2240
+ metadata_map["sampleFormat"] = quote_value(*stream_metadata.sample_format);
2241
+ metadata_map["codec"] = quote_value(*stream_metadata.codec_name);
2242
+ metadata_map["durationSeconds"] =
2243
+ fmt::to_string(*stream_metadata.duration_seconds_from_header);
2244
+ metadata_map["durationSecondsFromHeader"] =
2245
+ fmt::to_string(*stream_metadata.duration_seconds_from_header);
2246
+ metadata_map["bitRate"] = fmt::to_string(*stream_metadata.bit_rate);
2247
+ metadata_map["streamIndex"] = std::to_string(stream_metadata.stream_index);
2248
+ metadata_map["mediaType"] = quote_value("audio");
2249
+ metadata_map["beginStreamSeconds"] =
2250
+ fmt::to_string(*stream_metadata.begin_stream_pts_seconds_from_content);
2251
+ return map_to_json_tensor(metadata_map);
2252
+ }
2253
+
2254
+ void _set_nvdec_cache_capacity(int64_t capacity) {
2255
+ int capacity_int = validate_int64_to_int(capacity, "capacity");
2256
+ STD_TORCH_CHECK(
2257
+ capacity_int >= 0,
2258
+ "NVDEC cache capacity must be non-negative, got ",
2259
+ capacity_int);
2260
+ set_nvdec_cache_capacity(capacity_int);
2261
+ }
2262
+
2263
+ int64_t _get_nvdec_cache_capacity() {
2264
+ return static_cast<int64_t>(get_nvdec_cache_capacity());
2265
+ }
2266
+
2267
+ int64_t _get_nvdec_cache_size(int64_t device_index) {
2268
+ int device_index_int = validate_int64_to_int(device_index, "device_index");
2269
+ STD_TORCH_CHECK(
2270
+ device_index_int >= 0,
2271
+ "device_index must be non-negative, got ",
2272
+ device_index_int);
2273
+ return static_cast<int64_t>(get_nvdec_cache_size(device_index_int));
2274
+ }
2275
+
2276
+ void _set_cpp_log_level(int64_t level) {
2277
+ set_cpp_log_level(static_cast<LogLevel>(level));
2278
+ }
2279
+
2280
+ int64_t _get_log_level() {
2281
+ return static_cast<int64_t>(get_log_level());
2282
+ }
2283
+
2284
+ STABLE_TORCH_LIBRARY_IMPL(torchcodec_ns, BackendSelect, m) {
2285
+ m.impl("create_from_file", TORCH_BOX(&create_from_file));
2286
+ m.impl("create_from_tensor", TORCH_BOX(&create_from_tensor));
2287
+ m.impl("_create_from_file_like", TORCH_BOX(&_create_from_file_like));
2288
+ m.impl(
2289
+ "_blocks_create_demuxer_from_file",
2290
+ TORCH_BOX(&_blocks_create_demuxer_from_file));
2291
+ m.impl(
2292
+ "_blocks_create_demuxer_from_tensor",
2293
+ TORCH_BOX(&_blocks_create_demuxer_from_tensor));
2294
+ m.impl(
2295
+ "_blocks_create_demuxer_from_file_like",
2296
+ TORCH_BOX(&_blocks_create_demuxer_from_file_like));
2297
+ m.impl(
2298
+ "_blocks_create_color_converter",
2299
+ TORCH_BOX(&_blocks_create_color_converter));
2300
+ m.impl(
2301
+ "_blocks_create_packet_decoder",
2302
+ TORCH_BOX(&_blocks_create_packet_decoder));
2303
+ m.impl(
2304
+ "_blocks_create_audio_converter",
2305
+ TORCH_BOX(&_blocks_create_audio_converter));
2306
+ m.impl(
2307
+ "_get_json_ffmpeg_library_versions",
2308
+ TORCH_BOX(&_get_json_ffmpeg_library_versions));
2309
+ m.impl(
2310
+ "_blocks_get_ffmpeg_enum_name", TORCH_BOX(&_blocks_get_ffmpeg_enum_name));
2311
+ m.impl("create_streaming_encoder", TORCH_BOX(&create_streaming_encoder));
2312
+ m.impl(
2313
+ "streaming_encoder_add_video_stream",
2314
+ TORCH_BOX(&streaming_encoder_add_video_stream));
2315
+ m.impl(
2316
+ "streaming_encoder_add_audio_stream",
2317
+ TORCH_BOX(&streaming_encoder_add_audio_stream));
2318
+ m.impl(
2319
+ "streaming_encoder_open_file", TORCH_BOX(&streaming_encoder_open_file));
2320
+ m.impl(
2321
+ "streaming_encoder_open_file_like",
2322
+ TORCH_BOX(&streaming_encoder_open_file_like));
2323
+ m.impl(
2324
+ "streaming_encoder_add_frames", TORCH_BOX(&streaming_encoder_add_frames));
2325
+ m.impl(
2326
+ "streaming_encoder_add_samples",
2327
+ TORCH_BOX(&streaming_encoder_add_samples));
2328
+ m.impl("set_nvdec_cache_capacity", TORCH_BOX(&_set_nvdec_cache_capacity));
2329
+ m.impl("get_nvdec_cache_capacity", TORCH_BOX(&_get_nvdec_cache_capacity));
2330
+ m.impl("_get_nvdec_cache_size", TORCH_BOX(&_get_nvdec_cache_size));
2331
+ m.impl("_set_cpp_log_level", TORCH_BOX(&_set_cpp_log_level));
2332
+ m.impl("_get_log_level", TORCH_BOX(&_get_log_level));
2333
+ m.impl(
2334
+ "create_wav_decoder_from_file", TORCH_BOX(&create_wav_decoder_from_file));
2335
+ m.impl(
2336
+ "create_wav_decoder_from_tensor",
2337
+ TORCH_BOX(&create_wav_decoder_from_tensor));
2338
+ m.impl(
2339
+ "_create_wav_decoder_from_file_like",
2340
+ TORCH_BOX(&_create_wav_decoder_from_file_like));
2341
+ m.impl("get_wav_samples_in_range", TORCH_BOX(&get_wav_samples_in_range));
2342
+ m.impl(
2343
+ "get_wav_metadata_from_decoder",
2344
+ TORCH_BOX(&get_wav_metadata_from_decoder));
2345
+ }
2346
+
2347
+ STABLE_TORCH_LIBRARY_IMPL(torchcodec_ns, CPU, m) {
2348
+ m.impl("seek_to_pts", TORCH_BOX(&seek_to_pts));
2349
+ m.impl("add_video_stream", TORCH_BOX(&add_video_stream));
2350
+ m.impl("_add_video_stream", TORCH_BOX(&_add_video_stream));
2351
+ m.impl("add_audio_stream", TORCH_BOX(&add_audio_stream));
2352
+ m.impl("get_next_frame", TORCH_BOX(&get_next_frame));
2353
+ m.impl("_get_key_frame_indices", TORCH_BOX(&_get_key_frame_indices));
2354
+ m.impl("get_json_metadata", TORCH_BOX(&get_json_metadata));
2355
+ m.impl(
2356
+ "get_container_json_metadata", TORCH_BOX(&get_container_json_metadata));
2357
+ m.impl("get_stream_json_metadata", TORCH_BOX(&get_stream_json_metadata));
2358
+ m.impl("get_frame_at_pts", TORCH_BOX(&get_frame_at_pts));
2359
+ m.impl("get_frame_at_index", TORCH_BOX(&get_frame_at_index));
2360
+ m.impl("get_frames_at_indices", TORCH_BOX(&get_frames_at_indices));
2361
+ m.impl("get_frames_in_range", TORCH_BOX(&get_frames_in_range));
2362
+ m.impl("get_frames_by_pts_in_range", TORCH_BOX(&get_frames_by_pts_in_range));
2363
+ m.impl(
2364
+ "get_frames_by_pts_in_range_audio",
2365
+ TORCH_BOX(&get_frames_by_pts_in_range_audio));
2366
+ m.impl("get_frames_by_pts", TORCH_BOX(&get_frames_by_pts));
2367
+ m.impl("_blocks_demuxer_add_stream", TORCH_BOX(&_blocks_demuxer_add_stream));
2368
+ m.impl(
2369
+ "_blocks_demuxer_get_audio_video_stream_indices",
2370
+ TORCH_BOX(&_blocks_demuxer_get_audio_video_stream_indices));
2371
+ m.impl(
2372
+ "_blocks_demuxer_container_json_metadata",
2373
+ TORCH_BOX(&_blocks_demuxer_container_json_metadata));
2374
+ m.impl(
2375
+ "_blocks_demuxer_stream_json_metadata",
2376
+ TORCH_BOX(&_blocks_demuxer_stream_json_metadata));
2377
+ m.impl(
2378
+ "_blocks_demuxer_next_packet", TORCH_BOX(&_blocks_demuxer_next_packet));
2379
+ m.impl("_blocks_demuxer_seek", TORCH_BOX(&_blocks_demuxer_seek));
2380
+ m.impl("_blocks_demuxer_scan", TORCH_BOX(&_blocks_demuxer_scan));
2381
+ m.impl(
2382
+ "_blocks_demuxer_get_codec_parameters",
2383
+ TORCH_BOX(&_blocks_demuxer_get_codec_parameters));
2384
+ m.impl("_blocks_create_packet", TORCH_BOX(&_blocks_create_packet));
2385
+ m.impl("_blocks_packet_get_fields", TORCH_BOX(&_blocks_packet_get_fields));
2386
+ m.impl(
2387
+ "_blocks_packet_decoder_send_packet",
2388
+ TORCH_BOX(&_blocks_packet_decoder_send_packet));
2389
+ m.impl(
2390
+ "_blocks_packet_decoder_send_eof",
2391
+ TORCH_BOX(&_blocks_packet_decoder_send_eof));
2392
+ m.impl(
2393
+ "_blocks_packet_decoder_reset", TORCH_BOX(&_blocks_packet_decoder_reset));
2394
+ m.impl(
2395
+ "_blocks_packet_decoder_receive_frame",
2396
+ TORCH_BOX(&_blocks_packet_decoder_receive_frame));
2397
+ m.impl(
2398
+ "_blocks_audio_packet_decoder_receive_frame",
2399
+ TORCH_BOX(&_blocks_audio_packet_decoder_receive_frame));
2400
+ m.impl("_blocks_convert_frame", TORCH_BOX(&_blocks_convert_frame));
2401
+ m.impl(
2402
+ "_blocks_audio_converter_convert",
2403
+ TORCH_BOX(&_blocks_audio_converter_convert));
2404
+ m.impl(
2405
+ "_blocks_audio_converter_drain",
2406
+ TORCH_BOX(&_blocks_audio_converter_drain));
2407
+ m.impl(
2408
+ "_blocks_audio_converter_reset",
2409
+ TORCH_BOX(&_blocks_audio_converter_reset));
2410
+ m.impl("_blocks_frame_metadata", TORCH_BOX(&_blocks_frame_metadata));
2411
+ m.impl("_blocks_frame_planes", TORCH_BOX(&_blocks_frame_planes));
2412
+ m.impl("_test_frame_pts_equality", TORCH_BOX(&_test_frame_pts_equality));
2413
+ m.impl(
2414
+ "scan_all_streams_to_update_metadata",
2415
+ TORCH_BOX(&scan_all_streams_to_update_metadata));
2416
+
2417
+ m.impl("_get_backend_details", TORCH_BOX(&get_backend_details));
2418
+ m.impl("create_streaming_encoder", TORCH_BOX(&create_streaming_encoder));
2419
+ m.impl(
2420
+ "streaming_encoder_open_file", TORCH_BOX(&streaming_encoder_open_file));
2421
+ m.impl(
2422
+ "streaming_encoder_open_file_like",
2423
+ TORCH_BOX(&streaming_encoder_open_file_like));
2424
+ m.impl("streaming_encoder_close", TORCH_BOX(&streaming_encoder_close));
2425
+ m.impl(
2426
+ "streaming_encoder_add_video_stream",
2427
+ TORCH_BOX(&streaming_encoder_add_video_stream));
2428
+ m.impl(
2429
+ "streaming_encoder_add_audio_stream",
2430
+ TORCH_BOX(&streaming_encoder_add_audio_stream));
2431
+ m.impl(
2432
+ "streaming_encoder_add_frames", TORCH_BOX(&streaming_encoder_add_frames));
2433
+ m.impl(
2434
+ "streaming_encoder_add_samples",
2435
+ TORCH_BOX(&streaming_encoder_add_samples));
2436
+ }
2437
+
2438
+ } // namespace facebook::torchcodec