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
torchcodec/__init__.py ADDED
@@ -0,0 +1,50 @@
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
+ import os
8
+ from pathlib import Path
9
+
10
+ # Note: usort wants to put Frame and FrameBatch after decoders and samplers,
11
+ # but that results in circular import.
12
+ from ._frame import AudioSamples, Frame, FrameBatch # usort:skip # noqa
13
+ from . import decoders, encoders, samplers, transforms # noqa
14
+
15
+ try:
16
+ # Note that version.py is generated during install.
17
+ from .version import __version__ # noqa: F401
18
+ except Exception:
19
+ pass
20
+
21
+ # cmake_prefix_path is needed for downstream cmake-based builds that use
22
+ # torchcodec as a dependency to tell cmake where torchcodec is installed and where to find its
23
+ # CMake configuration files.
24
+ # Pytorch itself has a similar mechanism which we use in our setup.py!
25
+ cmake_prefix_path = Path(__file__).parent / "share" / "cmake"
26
+ # Similarly, these are exposed for downstream builds that use torchcodec as a
27
+ # dependency.
28
+ from ._core import core_library_path, ffmpeg_major_version # usort:skip
29
+
30
+
31
+ # Leverage the Python plugin mechanism to load out-of-the-tree device extensions.
32
+ # See https://github.com/pytorch/pytorch/pull/127074 that enabled the same
33
+ # plugin support in torch.
34
+ # This block should be kept at the end to ensure all the other functions in this
35
+ # module that may be accessed by an autoloaded backend are defined.
36
+ _TORCHCODEC_DEVICE_BACKEND_AUTOLOAD_VAR_NAME = "TORCHCODEC_DEVICE_BACKEND_AUTOLOAD"
37
+ if os.getenv(_TORCHCODEC_DEVICE_BACKEND_AUTOLOAD_VAR_NAME, "1") == "1":
38
+ from importlib.metadata import entry_points
39
+
40
+ _backend_extensions = entry_points(group="torchcodec.backends")
41
+
42
+ for _backend_extension in _backend_extensions:
43
+ try:
44
+ _entrypoint = _backend_extension.load()
45
+ _entrypoint()
46
+ except Exception as _err:
47
+ raise RuntimeError(
48
+ f"Failed to load the backend extension: {_backend_extension.name}. "
49
+ f"You can disable extension auto-loading with {_TORCHCODEC_DEVICE_BACKEND_AUTOLOAD_VAR_NAME}=0."
50
+ ) from _err
@@ -0,0 +1,85 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ // All rights reserved.
3
+ //
4
+ // This source code is licensed under the BSD-style license found in the
5
+ // LICENSE file in the root directory of this source tree.
6
+
7
+ #include "AVIOContextHolder.h"
8
+ #include "StableABICompat.h"
9
+
10
+ namespace facebook::torchcodec {
11
+
12
+ // --------------------------------------------------------------------------
13
+ // FFmpeg AVIO callbacks - delegate to the wrapped IOInterface via opaque
14
+ // --------------------------------------------------------------------------
15
+
16
+ int AVIOContextHolder::read_callback(void* opaque, uint8_t* buf, int buf_size) {
17
+ auto io = static_cast<IOInterface*>(opaque);
18
+ int result = io->read(buf, buf_size);
19
+ return result < 0 ? AVERROR_EOF : result;
20
+ }
21
+
22
+ int AVIOContextHolder::write_callback(
23
+ void* opaque,
24
+ const uint8_t* buf,
25
+ int buf_size) {
26
+ auto io = static_cast<IOInterface*>(opaque);
27
+ return io->write(buf, buf_size);
28
+ }
29
+
30
+ int64_t
31
+ AVIOContextHolder::seek_callback(void* opaque, int64_t offset, int whence) {
32
+ auto io = static_cast<IOInterface*>(opaque);
33
+ if (whence == AVSEEK_SIZE) {
34
+ int64_t size = io->get_size();
35
+ // INT64_MAX means "unknown size" (e.g. streaming file-like objects).
36
+ // Tell FFmpeg the size is unavailable rather than passing a bogus value.
37
+ return size == INT64_MAX ? AVERROR(EIO) : size;
38
+ }
39
+ return io->seek(offset, whence);
40
+ }
41
+
42
+ // --------------------------------------------------------------------------
43
+ // AVIO context creation and lifecycle
44
+ // --------------------------------------------------------------------------
45
+
46
+ AVIOContextHolder::AVIOContextHolder(
47
+ std::unique_ptr<IOInterface> io,
48
+ bool is_for_writing,
49
+ int buffer_size)
50
+ : io_(std::move(io)) {
51
+ STD_TORCH_CHECK(io_ != nullptr, "IOInterface must not be null");
52
+ STD_TORCH_CHECK(
53
+ buffer_size > 0,
54
+ "Buffer size must be greater than 0; is " + std::to_string(buffer_size));
55
+ auto buffer = static_cast<uint8_t*>(av_malloc(buffer_size));
56
+ STD_TORCH_CHECK(
57
+ buffer != nullptr,
58
+ "Failed to allocate buffer of size " + std::to_string(buffer_size));
59
+
60
+ avio_context_.reset(avio_alloc_context(
61
+ buffer,
62
+ buffer_size,
63
+ /*write_flag=*/is_for_writing,
64
+ /*opaque=*/io_.get(),
65
+ is_for_writing ? nullptr : &read_callback,
66
+ is_for_writing ? &write_callback : nullptr,
67
+ &seek_callback));
68
+
69
+ if (!avio_context_) {
70
+ av_freep(&buffer);
71
+ STD_TORCH_CHECK(false, "Failed to allocate AVIOContext");
72
+ }
73
+ }
74
+
75
+ AVIOContextHolder::~AVIOContextHolder() {
76
+ if (avio_context_) {
77
+ av_freep(&avio_context_->buffer);
78
+ }
79
+ }
80
+
81
+ AVIOContext* AVIOContextHolder::get_avio_context() {
82
+ return avio_context_.get();
83
+ }
84
+
85
+ } // namespace facebook::torchcodec
@@ -0,0 +1,44 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ // All rights reserved.
3
+ //
4
+ // This source code is licensed under the BSD-style license found in the
5
+ // LICENSE file in the root directory of this source tree.
6
+
7
+ #pragma once
8
+
9
+ #include <memory>
10
+ #include "FFMPEGCommon.h"
11
+ #include "IOInterface.h"
12
+ #include "StableABICompat.h"
13
+
14
+ namespace facebook::torchcodec {
15
+
16
+ // Adapts an FFmpeg-free IOInterface into an FFmpeg AVIOContext. It owns both
17
+ // the wrapped IOInterface and the AVIOContext (and the AVIOContext's buffer),
18
+ // freeing them on destruction. Used by SingleStreamDecoder and Encoder to
19
+ // feed/drain FFmpeg through a custom I/O backend (an in-memory tensor, a Python
20
+ // file-like object, ...): the AVIO callbacks delegate to the wrapped
21
+ // IOInterface's read/write/seek/get_size.
22
+ class FORCE_PUBLIC_VISIBILITY AVIOContextHolder {
23
+ public:
24
+ AVIOContextHolder(
25
+ std::unique_ptr<IOInterface> io,
26
+ bool is_for_writing,
27
+ int buffer_size = default_buffer_size);
28
+ ~AVIOContextHolder();
29
+
30
+ AVIOContext* get_avio_context();
31
+
32
+ private:
33
+ static int read_callback(void* opaque, uint8_t* buf, int buf_size);
34
+ static int write_callback(void* opaque, const uint8_t* buf, int buf_size);
35
+ static int64_t seek_callback(void* opaque, int64_t offset, int whence);
36
+
37
+ std::unique_ptr<IOInterface> io_;
38
+ UniqueAVIOContext avio_context_;
39
+
40
+ // Defaults to 64 KB
41
+ static const int default_buffer_size = 64 * 1024;
42
+ };
43
+
44
+ } // namespace facebook::torchcodec
@@ -0,0 +1,101 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ // All rights reserved.
3
+ //
4
+ // This source code is licensed under the BSD-style license found in the
5
+ // LICENSE file in the root directory of this source tree.
6
+
7
+ #include "AudioCommon.h"
8
+
9
+ #include <vector>
10
+
11
+ namespace facebook::torchcodec {
12
+
13
+ torch::headeronly::ScalarType sample_format_dtype(
14
+ AVSampleFormat sample_format) {
15
+ switch (av_get_packed_sample_fmt(sample_format)) {
16
+ case AV_SAMPLE_FMT_U8:
17
+ return kStableUInt8;
18
+ case AV_SAMPLE_FMT_S16:
19
+ return kStableInt16;
20
+ case AV_SAMPLE_FMT_S32:
21
+ return kStableInt32;
22
+ case AV_SAMPLE_FMT_S64:
23
+ return kStableInt64;
24
+ case AV_SAMPLE_FMT_FLT:
25
+ return kStableFloat32;
26
+ case AV_SAMPLE_FMT_DBL:
27
+ return kStableFloat64;
28
+ default:
29
+ break;
30
+ }
31
+ const char* name = av_get_sample_fmt_name(sample_format);
32
+ STD_TORCH_CHECK(
33
+ false,
34
+ "Unsupported sample format '",
35
+ name == nullptr ? "unknown" : name,
36
+ "'.");
37
+ return kStableUInt8;
38
+ }
39
+
40
+ AVSampleFormat planar_sample_format(torch::headeronly::ScalarType dtype) {
41
+ switch (dtype) {
42
+ case kStableUInt8:
43
+ return AV_SAMPLE_FMT_U8P;
44
+ case kStableInt16:
45
+ return AV_SAMPLE_FMT_S16P;
46
+ case kStableInt32:
47
+ return AV_SAMPLE_FMT_S32P;
48
+ case kStableInt64:
49
+ return AV_SAMPLE_FMT_S64P;
50
+ case kStableFloat32:
51
+ return AV_SAMPLE_FMT_FLTP;
52
+ case kStableFloat64:
53
+ return AV_SAMPLE_FMT_DBLP;
54
+ default:
55
+ break;
56
+ }
57
+ STD_TORCH_CHECK(
58
+ false,
59
+ "Unsupported dtype for audio samples. Expected one of uint8, int16, "
60
+ "int32, int64, float32 or float64.");
61
+ return AV_SAMPLE_FMT_NONE;
62
+ }
63
+
64
+ torch::stable::Tensor swr_convert_to_tensor(
65
+ const UniqueSwrContext& swr_context,
66
+ const uint8_t** src_planes,
67
+ int num_src_samples,
68
+ int num_out_channels,
69
+ int64_t num_out_samples_bound) {
70
+ torch::stable::Tensor out = torch::stable::empty(
71
+ {num_out_channels, num_out_samples_bound}, kStableFloat32);
72
+ if (num_out_samples_bound == 0) {
73
+ return out;
74
+ }
75
+
76
+ // A contiguous [num_out_channels, N] float32 tensor is exactly FLTP: one
77
+ // plane per row.
78
+ int64_t bytes_per_channel =
79
+ num_out_samples_bound * av_get_bytes_per_sample(kAudioOutSampleFormat);
80
+ auto* base = static_cast<uint8_t*>(out.mutable_data_ptr());
81
+ std::vector<uint8_t*> out_planes(num_out_channels);
82
+ for (int channel = 0; channel < num_out_channels; ++channel) {
83
+ out_planes[channel] = base + channel * bytes_per_channel;
84
+ }
85
+
86
+ int num_out_samples = swr_convert(
87
+ swr_context.get(),
88
+ out_planes.data(),
89
+ static_cast<int>(num_out_samples_bound),
90
+ src_planes,
91
+ num_src_samples);
92
+ STD_TORCH_CHECK(
93
+ num_out_samples >= 0,
94
+ "Error in swr_convert: ",
95
+ get_ffmpeg_error_string_from_error_code(num_out_samples));
96
+
97
+ return torch::stable::narrow(
98
+ out, /*dim=*/1, /*start=*/0, /*length=*/num_out_samples);
99
+ }
100
+
101
+ } // namespace facebook::torchcodec
@@ -0,0 +1,48 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ // All rights reserved.
3
+ //
4
+ // This source code is licensed under the BSD-style license found in the
5
+ // LICENSE file in the root directory of this source tree.
6
+
7
+ #pragma once
8
+
9
+ #include "FFMPEGCommon.h"
10
+ #include "StableABICompat.h"
11
+
12
+ // Where FFmpeg's audio samples meet torch tensors. FFMPEGCommon deliberately
13
+ // knows nothing about tensors, and these helpers are shared by the decode, the
14
+ // conversion and the SingleStreamDecoder paths, so they live on their own.
15
+
16
+ namespace facebook::torchcodec {
17
+
18
+ // Decoded audio always leaves torchcodec as normalized float32 samples,
19
+ // one plane per channel.
20
+ constexpr AVSampleFormat kAudioOutSampleFormat = AV_SAMPLE_FMT_FLTP;
21
+
22
+ // The dtype that holds `sample_format`'s samples exactly. Planar and packed
23
+ // variants of a format share a sample type, which is why this doesn't care
24
+ // which one it is given.
25
+ torch::headeronly::ScalarType sample_format_dtype(AVSampleFormat sample_format);
26
+
27
+ // The inverse: the sample format that a contiguous [num_channels, num_samples]
28
+ // tensor of `dtype` already is. One row per channel is precisely what planar
29
+ // means, which is what lets swresample read such a tensor's rows directly.
30
+ AVSampleFormat planar_sample_format(torch::headeronly::ScalarType dtype);
31
+
32
+ // Runs swr_convert() straight into a fresh float32 [num_out_channels, N]
33
+ // tensor, narrowed to the number of samples it actually produced - which is
34
+ // at most `num_out_samples_bound` and is often fewer, since swresample holds
35
+ // back the samples that need future input. Pass a null `src_planes` to flush
36
+ // those out.
37
+ //
38
+ // `src_planes` is deliberately `const uint8_t**` rather than
39
+ // `const uint8_t* const*`: swr_convert() takes the former up to FFmpeg 6 and
40
+ // the latter from 7 on, and only the former converts to both.
41
+ torch::stable::Tensor swr_convert_to_tensor(
42
+ const UniqueSwrContext& swr_context,
43
+ const uint8_t** src_planes,
44
+ int num_src_samples,
45
+ int num_out_channels,
46
+ int64_t num_out_samples_bound);
47
+
48
+ } // namespace facebook::torchcodec
@@ -0,0 +1,130 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ // All rights reserved.
3
+ //
4
+ // This source code is licensed under the BSD-style license found in the
5
+ // LICENSE file in the root directory of this source tree.
6
+
7
+ #include "AudioConverter.h"
8
+
9
+ #include <vector>
10
+
11
+ #include "AudioCommon.h"
12
+
13
+ namespace facebook::torchcodec {
14
+
15
+ AudioConverter::AudioConverter(
16
+ std::optional<int> sample_rate,
17
+ std::optional<int> num_channels)
18
+ : requested_sample_rate_(sample_rate),
19
+ requested_num_channels_(num_channels) {
20
+ STD_TORCH_CHECK(
21
+ !sample_rate.has_value() || *sample_rate > 0,
22
+ "sample_rate must be > 0. Got: ",
23
+ sample_rate.value_or(0));
24
+ STD_TORCH_CHECK(
25
+ !num_channels.has_value() || *num_channels > 0,
26
+ "num_channels must be > 0. Got: ",
27
+ num_channels.value_or(0));
28
+ }
29
+
30
+ void AudioConverter::reset() {
31
+ swr_context_.reset();
32
+ src_sample_format_ = AV_SAMPLE_FMT_NONE;
33
+ src_sample_rate_ = 0;
34
+ src_num_channels_ = 0;
35
+ out_sample_rate_ = 0;
36
+ out_num_channels_ = 0;
37
+ }
38
+
39
+ torch::stable::Tensor AudioConverter::convert(
40
+ const torch::stable::Tensor& samples,
41
+ int sample_rate) {
42
+ STD_TORCH_CHECK(
43
+ samples.dim() == 2,
44
+ "Expected a 2D [num_channels, num_samples] tensor, got a ",
45
+ samples.dim(),
46
+ "D one.");
47
+ STD_TORCH_CHECK(samples.is_contiguous(), "The samples must be contiguous.");
48
+ STD_TORCH_CHECK(sample_rate > 0, "sample_rate must be > 0.");
49
+
50
+ AVSampleFormat src_sample_format =
51
+ planar_sample_format(samples.scalar_type());
52
+ int num_channels = static_cast<int>(samples.sizes()[0]);
53
+ int num_samples = static_cast<int>(samples.sizes()[1]);
54
+ STD_TORCH_CHECK(
55
+ num_channels > 0, "The samples must have at least 1 channel.");
56
+
57
+ if (swr_context_ == nullptr) {
58
+ src_sample_format_ = src_sample_format;
59
+ src_sample_rate_ = sample_rate;
60
+ src_num_channels_ = num_channels;
61
+ out_sample_rate_ = requested_sample_rate_.value_or(sample_rate);
62
+ out_num_channels_ = requested_num_channels_.value_or(num_channels);
63
+ swr_context_.reset(create_swr_context(
64
+ src_sample_format_,
65
+ kAudioOutSampleFormat,
66
+ src_sample_rate_,
67
+ out_sample_rate_,
68
+ src_num_channels_,
69
+ out_num_channels_));
70
+ } else {
71
+ // swresample is configured once, from the first samples we see, and its
72
+ // buffered state is tied to that configuration. Rather than silently
73
+ // reconfiguring - which would discard whatever it still holds - we make the
74
+ // caller decide, by reset()ing.
75
+ STD_TORCH_CHECK(
76
+ src_sample_format == src_sample_format_ &&
77
+ sample_rate == src_sample_rate_ &&
78
+ num_channels == src_num_channels_,
79
+ "This AudioConverter was set up for ",
80
+ src_num_channels_,
81
+ " channels of ",
82
+ av_get_sample_fmt_name(src_sample_format_),
83
+ " at ",
84
+ src_sample_rate_,
85
+ " Hz, but got ",
86
+ num_channels,
87
+ " channels of ",
88
+ av_get_sample_fmt_name(src_sample_format),
89
+ " at ",
90
+ sample_rate,
91
+ " Hz. Call reset() to convert a different stream.");
92
+ }
93
+
94
+ const auto* base = static_cast<const uint8_t*>(samples.const_data_ptr());
95
+ int64_t bytes_per_channel =
96
+ num_samples * av_get_bytes_per_sample(src_sample_format);
97
+ std::vector<const uint8_t*> src_planes(num_channels);
98
+ for (int channel = 0; channel < num_channels; ++channel) {
99
+ src_planes[channel] = base + channel * bytes_per_channel;
100
+ }
101
+
102
+ // TODO_API_BREAKDOWN CC P2: the CPUDeviceInterface relies on
103
+ // swr_convert_to_tensor but only for flushing. We effectively have two
104
+ // code-paths doing libswresample conversion. Worth aligning.
105
+ return swr_convert_to_tensor(
106
+ swr_context_,
107
+ src_planes.data(),
108
+ num_samples,
109
+ out_num_channels_,
110
+ get_swr_output_num_samples_bound(
111
+ swr_context_, num_samples, src_sample_rate_, out_sample_rate_));
112
+ }
113
+
114
+ torch::stable::Tensor AudioConverter::drain() {
115
+ STD_TORCH_CHECK(
116
+ swr_context_ != nullptr,
117
+ "This AudioConverter hasn't converted any samples, so there is nothing "
118
+ "to drain and no way to know what shape the result should have.");
119
+ // A null input is what tells swr_convert() to flush. Unlike the convert()
120
+ // path we ask swresample how much it is holding rather than deriving a bound
121
+ // from an input size, since here there is no input.
122
+ return swr_convert_to_tensor(
123
+ swr_context_,
124
+ /*src_planes=*/nullptr,
125
+ /*num_src_samples=*/0,
126
+ out_num_channels_,
127
+ swr_get_out_samples(swr_context_.get(), 0));
128
+ }
129
+
130
+ } // namespace facebook::torchcodec
@@ -0,0 +1,59 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ // All rights reserved.
3
+ //
4
+ // This source code is licensed under the BSD-style license found in the
5
+ // LICENSE file in the root directory of this source tree.
6
+
7
+ #pragma once
8
+
9
+ #include <optional>
10
+
11
+ #include "FFMPEGCommon.h"
12
+ #include "StableABICompat.h"
13
+
14
+ namespace facebook::torchcodec {
15
+
16
+ // Audio conversion building block: turns a decoded frame's samples, in the
17
+ // codec's own sample type, into normalized float32 ones - optionally at another
18
+ // sample rate, and with another channel count.
19
+
20
+ // Not thread-safe.
21
+ class FORCE_PUBLIC_VISIBILITY AudioConverter {
22
+ public:
23
+ explicit AudioConverter(
24
+ std::optional<int> sample_rate = std::nullopt,
25
+ std::optional<int> num_channels = std::nullopt);
26
+
27
+ torch::stable::Tensor convert(
28
+ const torch::stable::Tensor& samples,
29
+ int sample_rate);
30
+
31
+ torch::stable::Tensor drain();
32
+
33
+ void reset();
34
+
35
+ bool has_converted_samples() const {
36
+ return swr_context_ != nullptr;
37
+ }
38
+
39
+ // Only meaningful once convert() has been called at least once.
40
+ int out_sample_rate() const {
41
+ return out_sample_rate_;
42
+ }
43
+
44
+ private:
45
+ std::optional<int> requested_sample_rate_;
46
+ std::optional<int> requested_num_channels_;
47
+
48
+ UniqueSwrContext swr_context_;
49
+ // All of these are set when swr_context_ is created, and describe what it was
50
+ // configured for. The src_ ones are what a later convert() is checked
51
+ // against: swresample is built once for one input shape.
52
+ AVSampleFormat src_sample_format_ = AV_SAMPLE_FMT_NONE;
53
+ int src_sample_rate_ = 0;
54
+ int src_num_channels_ = 0;
55
+ int out_sample_rate_ = 0;
56
+ int out_num_channels_ = 0;
57
+ };
58
+
59
+ } // namespace facebook::torchcodec