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,131 @@
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
+
8
+ import io
9
+ import json
10
+ from fractions import Fraction
11
+ from pathlib import Path
12
+
13
+ import torch
14
+ from torchcodec import _core, AudioSamples
15
+ from torchcodec._core._decoder_utils import create_wav_decoder
16
+ from torchcodec._core._metadata import AudioStreamMetadata
17
+
18
+
19
+ class WavDecoder:
20
+ """A fast decoder for WAV audio files.
21
+
22
+ This is a lightweight, high-performance alternative to
23
+ :class:`~torchcodec.decoders.AudioDecoder` that is specialized for WAV
24
+ files. See :ref:`sphx_glr_generated_examples_decoding_performance_tips.py`
25
+ for more details.
26
+
27
+ Unlike :class:`~torchcodec.decoders.AudioDecoder`, this decoder does not
28
+ support resampling (``sample_rate`` parameter) or channel remixing
29
+ (``num_channels`` parameter). If you need those features, use
30
+ :class:`~torchcodec.decoders.AudioDecoder`.
31
+
32
+ Returned samples are float samples normalized in [-1, 1].
33
+
34
+ Args:
35
+ source (str, ``Pathlib.path``, bytes, ``torch.Tensor`` or file-like
36
+ object): The source of the audio:
37
+
38
+ - If ``str``: a path to a local WAV file.
39
+ - If ``Pathlib.path``: a path to a local WAV file.
40
+ - If ``bytes`` object or ``torch.Tensor``: the raw WAV data.
41
+ - If file-like object: we read audio data from the object on
42
+ demand. The object must expose the methods ``read(self, size:
43
+ int) -> bytes`` and ``seek(self, offset: int, whence: int) ->
44
+ int``.
45
+
46
+ Attributes:
47
+ metadata (AudioStreamMetadata): Metadata of the audio stream.
48
+ stream_index (int): The stream index. Always 0 for WAV files.
49
+ """
50
+
51
+ def __init__(
52
+ self,
53
+ source: str | Path | io.RawIOBase | io.BufferedReader | bytes | torch.Tensor,
54
+ ):
55
+ torch._C._log_api_usage_once("torchcodec.decoders.WavDecoder")
56
+
57
+ self._decoder = create_wav_decoder(source)
58
+ self._source = source
59
+ self.stream_index = 0
60
+
61
+ metadata_json = _core.get_wav_metadata_from_decoder(self._decoder)
62
+ metadata_dict = json.loads(metadata_json)
63
+
64
+ self.metadata = AudioStreamMetadata(
65
+ sample_rate=metadata_dict["sampleRate"],
66
+ num_channels=metadata_dict["numChannels"],
67
+ sample_format=metadata_dict["sampleFormat"],
68
+ duration_seconds=metadata_dict["durationSeconds"],
69
+ stream_index=metadata_dict["streamIndex"],
70
+ media_type=metadata_dict["mediaType"],
71
+ codec=metadata_dict["codec"],
72
+ # FFmpeg's WAV demuxer counts timestamps in samples.
73
+ time_base=Fraction(1, metadata_dict["sampleRate"]),
74
+ bit_rate=metadata_dict["bitRate"],
75
+ duration_seconds_from_header=metadata_dict["durationSecondsFromHeader"],
76
+ begin_stream_seconds=metadata_dict["beginStreamSeconds"],
77
+ begin_stream_seconds_from_header=None, # WAV format lacks stream start time metadata
78
+ )
79
+
80
+ def get_all_samples(self) -> AudioSamples:
81
+ """Returns all the audio samples from the source.
82
+
83
+ To decode samples in a specific range, use
84
+ :meth:`~torchcodec.decoders.WavDecoder.get_samples_played_in_range`.
85
+
86
+ Returns:
87
+ AudioSamples: The samples within the file.
88
+ """
89
+ return self.get_samples_played_in_range()
90
+
91
+ def get_samples_played_in_range(
92
+ self, start_seconds: float = 0.0, stop_seconds: float | None = None
93
+ ) -> AudioSamples:
94
+ """Returns audio samples in the given range.
95
+
96
+ Samples are in the half open range [start_seconds, stop_seconds).
97
+
98
+ To decode all the samples from beginning to end, you can call this
99
+ method while leaving ``start_seconds`` and ``stop_seconds`` to their
100
+ default values, or use
101
+ :meth:`~torchcodec.decoders.WavDecoder.get_all_samples` as a more
102
+ convenient alias.
103
+
104
+ Args:
105
+ start_seconds (float): Time, in seconds, of the start of the
106
+ range. Default: 0.
107
+ stop_seconds (float or None): Time, in seconds, of the end of the
108
+ range. As a half open range, the end is excluded. Default: None,
109
+ which decodes samples until the end.
110
+
111
+ Returns:
112
+ AudioSamples: The samples within the specified range.
113
+ """
114
+ if stop_seconds is not None and not start_seconds <= stop_seconds:
115
+ raise ValueError(
116
+ f"Invalid start seconds: {start_seconds}. It must be less than or equal to stop seconds ({stop_seconds})."
117
+ )
118
+
119
+ actual_start_seconds = max(0.0, start_seconds)
120
+ samples, actual_pts = _core.get_wav_samples_in_range(
121
+ self._decoder, actual_start_seconds, stop_seconds
122
+ )
123
+ actual_pts = actual_pts.item()
124
+ assert self.metadata.sample_rate is not None # make mypy happy
125
+ duration_seconds = samples.shape[1] / self.metadata.sample_rate
126
+ return AudioSamples(
127
+ data=samples,
128
+ pts_seconds=actual_pts,
129
+ duration_seconds=duration_seconds,
130
+ sample_rate=self.metadata.sample_rate,
131
+ )
@@ -0,0 +1,4 @@
1
+ from ._audio_encoder import AudioEncoder # noqa
2
+ from ._image_encoders import JpegEncoder, PngEncoder # noqa
3
+ from ._multi_stream_encoder import AudioStream, Encoder, VideoStream # noqa
4
+ from ._video_encoder import VideoEncoder # noqa
@@ -0,0 +1,167 @@
1
+ import io
2
+ from pathlib import Path
3
+
4
+ import torch
5
+ from torch import Tensor
6
+
7
+ from torchcodec._internally_replaced_utils import load_core_libraries
8
+ from torchcodec.encoders._multi_stream_encoder import Encoder
9
+
10
+
11
+ class AudioEncoder:
12
+ """A single-stream audio encoder.
13
+
14
+ .. note::
15
+ This is a convenience class for simple, one-shot audio encoding. For
16
+ multi-stream encoding (e.g. video + audio), incremental encoding, or
17
+ encoding multiple audio streams, use
18
+ :class:`~torchcodec.encoders.Encoder` instead. See
19
+ :ref:`sphx_glr_generated_examples_encoding_multi_stream_encoding.py` for
20
+ a tutorial.
21
+
22
+ Args:
23
+ samples (``torch.Tensor``): The samples to encode. This must be a 2D
24
+ tensor of shape ``(num_channels, num_samples)``, or a 1D tensor in
25
+ which case ``num_channels = 1`` is assumed. Values must be float
26
+ values in ``[-1, 1]``.
27
+ sample_rate (int): The sample rate of the **input** ``samples``. The
28
+ sample rate of the encoded output can be specified using the
29
+ encoding methods (``to_file``, etc.).
30
+ """
31
+
32
+ def __init__(self, samples: Tensor, *, sample_rate: int):
33
+ torch._C._log_api_usage_once("torchcodec.encoders.AudioEncoder")
34
+ load_core_libraries()
35
+ # Some of these checks are also done in C++: it's OK, they're cheap, and
36
+ # doing them here allows to surface them when the AudioEncoder is
37
+ # instantiated, rather than later when the encoding methods are called.
38
+ if not isinstance(samples, Tensor):
39
+ raise ValueError(
40
+ f"Expected samples to be a Tensor, got {type(samples) = }."
41
+ )
42
+ if samples.ndim == 1:
43
+ # make it 2D and assume 1 channel
44
+ samples = torch.unsqueeze(samples, 0)
45
+ if samples.ndim != 2:
46
+ raise ValueError(f"Expected 1D or 2D samples, got {samples.shape = }.")
47
+ if samples.dtype != torch.float32:
48
+ raise ValueError(f"Expected float32 samples, got {samples.dtype = }.")
49
+ if sample_rate <= 0:
50
+ raise ValueError(f"{sample_rate = } must be > 0.")
51
+
52
+ self._samples = samples
53
+ self._sample_rate = sample_rate
54
+
55
+ def to_file(
56
+ self,
57
+ dest: str | Path,
58
+ *,
59
+ bit_rate: int | None = None,
60
+ num_channels: int | None = None,
61
+ sample_rate: int | None = None,
62
+ ) -> None:
63
+ """Encode samples into a file.
64
+
65
+ Args:
66
+ dest (str or ``pathlib.Path``): The path to the output file, e.g.
67
+ ``audio.mp3``. The extension of the file determines the audio
68
+ format and container.
69
+ bit_rate (int, optional): The output bit rate. Encoders typically
70
+ support a finite set of bit rate values, so ``bit_rate`` will be
71
+ matched to one of those supported values. The default is chosen
72
+ by FFmpeg.
73
+ num_channels (int, optional): The number of channels of the encoded
74
+ output samples. By default, the number of channels of the input
75
+ ``samples`` is used.
76
+ sample_rate (int, optional): The sample rate of the encoded output.
77
+ By default, the sample rate of the input ``samples`` is used.
78
+ """
79
+ encoder = Encoder()
80
+ audio = encoder.add_audio(
81
+ sample_rate=self._sample_rate,
82
+ num_channels=self._samples.shape[0],
83
+ bit_rate=bit_rate,
84
+ out_num_channels=num_channels,
85
+ out_sample_rate=sample_rate,
86
+ )
87
+ with encoder.open_file(dest):
88
+ audio.add_samples(self._samples)
89
+
90
+ def to_tensor(
91
+ self,
92
+ format: str,
93
+ *,
94
+ bit_rate: int | None = None,
95
+ num_channels: int | None = None,
96
+ sample_rate: int | None = None,
97
+ ) -> Tensor:
98
+ """Encode samples into raw bytes, as a 1D uint8 Tensor.
99
+
100
+ Args:
101
+ format (str): The format of the encoded samples, e.g. "mp3", "wav"
102
+ or "flac".
103
+ bit_rate (int, optional): The output bit rate. Encoders typically
104
+ support a finite set of bit rate values, so ``bit_rate`` will be
105
+ matched to one of those supported values. The default is chosen
106
+ by FFmpeg.
107
+ num_channels (int, optional): The number of channels of the encoded
108
+ output samples. By default, the number of channels of the input
109
+ ``samples`` is used.
110
+ sample_rate (int, optional): The sample rate of the encoded output.
111
+ By default, the sample rate of the input ``samples`` is used.
112
+
113
+ Returns:
114
+ Tensor: The raw encoded bytes as 1D uint8 Tensor.
115
+ """
116
+ buf = io.BytesIO()
117
+ encoder = Encoder()
118
+ audio = encoder.add_audio(
119
+ sample_rate=self._sample_rate,
120
+ num_channels=self._samples.shape[0],
121
+ bit_rate=bit_rate,
122
+ out_num_channels=num_channels,
123
+ out_sample_rate=sample_rate,
124
+ )
125
+ with encoder.open_file_like(buf, format=format):
126
+ audio.add_samples(self._samples)
127
+ return torch.frombuffer(buf.getbuffer(), dtype=torch.uint8)
128
+
129
+ def to_file_like(
130
+ self,
131
+ file_like,
132
+ format: str,
133
+ *,
134
+ bit_rate: int | None = None,
135
+ num_channels: int | None = None,
136
+ sample_rate: int | None = None,
137
+ ) -> None:
138
+ """Encode samples into a file-like object.
139
+
140
+ Args:
141
+ file_like: A file-like object that supports ``write()`` and
142
+ ``seek()`` methods, such as io.BytesIO(), an open file in binary
143
+ write mode, etc. Methods must have the following signature:
144
+ ``write(data: bytes) -> int`` and ``seek(offset: int, whence:
145
+ int = 0) -> int``.
146
+ format (str): The format of the encoded samples, e.g. "mp3", "wav"
147
+ or "flac".
148
+ bit_rate (int, optional): The output bit rate. Encoders typically
149
+ support a finite set of bit rate values, so ``bit_rate`` will be
150
+ matched to one of those supported values. The default is chosen
151
+ by FFmpeg.
152
+ num_channels (int, optional): The number of channels of the encoded
153
+ output samples. By default, the number of channels of the input
154
+ ``samples`` is used.
155
+ sample_rate (int, optional): The sample rate of the encoded output.
156
+ By default, the sample rate of the input ``samples`` is used.
157
+ """
158
+ encoder = Encoder()
159
+ audio = encoder.add_audio(
160
+ sample_rate=self._sample_rate,
161
+ num_channels=self._samples.shape[0],
162
+ bit_rate=bit_rate,
163
+ out_num_channels=num_channels,
164
+ out_sample_rate=sample_rate,
165
+ )
166
+ with encoder.open_file_like(file_like, format=format):
167
+ audio.add_samples(self._samples)
@@ -0,0 +1,181 @@
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 io
8
+ from pathlib import Path
9
+
10
+ import torch
11
+ from torch import Tensor
12
+
13
+ from torchcodec._core.ops import (
14
+ create_file_like_context,
15
+ encode_jpeg_to_file as _encode_jpeg_to_file,
16
+ encode_jpeg_to_file_like as _encode_jpeg_to_file_like,
17
+ encode_jpeg_to_tensor_cuda as _encode_jpeg_to_tensor_cuda,
18
+ encode_png_to_file as _encode_png_to_file,
19
+ encode_png_to_file_like as _encode_png_to_file_like,
20
+ )
21
+
22
+
23
+ def _encode_to_tensor_through_bytesio(img, param, to_file_like) -> Tensor:
24
+ # Encode into an in-memory BytesIO and wrap its buffer as a 1-D uint8 tensor.
25
+ # getbuffer() (unlike getvalue()) exposes the buffer without copying. We
26
+ # could have native C++ implementation for that in each encoder, but it's
27
+ # not always worth it (based on benchmarks). Currently, the only encoder
28
+ # that really needs a dedicated C++ path is JPEG on CUDA.
29
+ buf = io.BytesIO()
30
+ to_file_like(img, create_file_like_context(buf, True), param)
31
+ return torch.frombuffer(buf.getbuffer(), dtype=torch.uint8)
32
+
33
+
34
+ class JpegEncoder:
35
+ """Encoder for JPEG images.
36
+
37
+ For a tutorial, see:
38
+ :ref:`sphx_glr_generated_examples_encoding_image_encoding.py`.
39
+
40
+ Example:
41
+
42
+ .. code-block:: python
43
+
44
+ from torchcodec.encoders import JpegEncoder
45
+
46
+ JpegEncoder(img).to_file("image.jpg")
47
+ # or encode to a file-like object or to a tensor, see methods below.
48
+
49
+ Args:
50
+ img (``torch.Tensor``): The image to encode, a 3-dimensional uint8 tensor
51
+ in CHW layout with 1 (grayscale) or 3 (RGB) channels. If on a CUDA
52
+ device, encoding is performed on the GPU with nvJPEG, and only
53
+ 3-channel RGB is supported.
54
+ """
55
+
56
+ def __init__(self, img: Tensor) -> None:
57
+ self._img = img
58
+
59
+ def to_file(self, dest: str | Path, *, quality: int = 75) -> None:
60
+ """Encode the image into a JPEG file.
61
+
62
+ Args:
63
+ dest (str or ``pathlib.Path``): The path to the output file, e.g.
64
+ ``image.jpg``.
65
+ quality (int, optional): Quality of the output, between 1 and 100.
66
+ Higher means better quality and larger file size. Default: 75.
67
+ """
68
+ self._validate_quality(quality)
69
+ _encode_jpeg_to_file(self._img, str(dest), quality)
70
+
71
+ def to_file_like(
72
+ self, dest: io.RawIOBase | io.BufferedIOBase, *, quality: int = 75
73
+ ) -> None:
74
+ """Encode the image into a file-like object.
75
+
76
+ Args:
77
+ dest: A writable file-like object supporting ``write`` and ``seek``,
78
+ such as ``io.BytesIO()`` or an open file in binary write mode.
79
+ quality (int, optional): Quality of the output, between 1 and 100.
80
+ Higher means better quality and larger file size. Default: 75.
81
+ """
82
+ self._validate_quality(quality)
83
+ _encode_jpeg_to_file_like(
84
+ self._img, create_file_like_context(dest, True), quality
85
+ )
86
+
87
+ def to_tensor(self, *, quality: int = 75) -> Tensor:
88
+ """Encode the image into raw bytes, as a 1D uint8 tensor.
89
+
90
+ The returned tensor is on the same device as the input image (a CUDA
91
+ input yields a CUDA tensor).
92
+
93
+ Args:
94
+ quality (int, optional): Quality of the output, between 1 and 100.
95
+ Higher means better quality and larger file size. Default: 75.
96
+
97
+ Returns:
98
+ torch.Tensor: The encoded bytes, a 1D uint8 tensor on the same
99
+ device as the input image.
100
+ """
101
+ self._validate_quality(quality)
102
+ if self._img.is_cuda:
103
+ return _encode_jpeg_to_tensor_cuda(self._img, quality)
104
+ else:
105
+ return _encode_to_tensor_through_bytesio(
106
+ self._img, quality, _encode_jpeg_to_file_like
107
+ )
108
+
109
+ @staticmethod
110
+ def _validate_quality(quality: int) -> None:
111
+ if quality < 1 or quality > 100:
112
+ raise ValueError(
113
+ "Image quality should be a positive number between 1 and 100"
114
+ )
115
+
116
+
117
+ class PngEncoder:
118
+ """Encoder for PNG images.
119
+
120
+ For a tutorial, see:
121
+ :ref:`sphx_glr_generated_examples_encoding_image_encoding.py`.
122
+
123
+ Example:
124
+
125
+ .. code-block:: python
126
+
127
+ from torchcodec.encoders import PngEncoder
128
+
129
+ PngEncoder(img).to_file("image.png")
130
+ # or encode to a file-like object or to a tensor, see methods below.
131
+
132
+ Args:
133
+ img (``torch.Tensor``): The image to encode, a 3-dimensional uint8 tensor
134
+ in CHW layout with 1 (grayscale) or 3 (RGB) channels.
135
+ """
136
+
137
+ def __init__(self, img: Tensor) -> None:
138
+ self._img = img
139
+
140
+ def to_file(self, dest: str | Path, *, compression_level: int = 6) -> None:
141
+ """Encode the image into a PNG file.
142
+
143
+ Args:
144
+ dest (str or ``pathlib.Path``): The path to the output file, e.g.
145
+ ``image.png``.
146
+ compression_level (int, optional): zlib compression level between 0
147
+ (no compression, fastest) and 9 (max compression, slowest).
148
+ Default: 6.
149
+ """
150
+ _encode_png_to_file(self._img, str(dest), compression_level)
151
+
152
+ def to_file_like(
153
+ self, dest: io.RawIOBase | io.BufferedIOBase, *, compression_level: int = 6
154
+ ) -> None:
155
+ """Encode the image into a file-like object.
156
+
157
+ Args:
158
+ dest: A writable file-like object supporting ``write`` and ``seek``,
159
+ such as ``io.BytesIO()`` or an open file in binary write mode.
160
+ compression_level (int, optional): zlib compression level between 0
161
+ (no compression, fastest) and 9 (max compression, slowest).
162
+ Default: 6.
163
+ """
164
+ _encode_png_to_file_like(
165
+ self._img, create_file_like_context(dest, True), compression_level
166
+ )
167
+
168
+ def to_tensor(self, *, compression_level: int = 6) -> Tensor:
169
+ """Encode the image into raw bytes, as a 1D uint8 tensor.
170
+
171
+ Args:
172
+ compression_level (int, optional): zlib compression level between 0
173
+ (no compression, fastest) and 9 (max compression, slowest).
174
+ Default: 6.
175
+
176
+ Returns:
177
+ torch.Tensor: The encoded bytes, a 1D uint8 tensor.
178
+ """
179
+ return _encode_to_tensor_through_bytesio(
180
+ self._img, compression_level, _encode_png_to_file_like
181
+ )