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.
- torchcodec/__init__.py +50 -0
- torchcodec/_core/AVIOContextHolder.cpp +85 -0
- torchcodec/_core/AVIOContextHolder.h +44 -0
- torchcodec/_core/AudioCommon.cpp +101 -0
- torchcodec/_core/AudioCommon.h +48 -0
- torchcodec/_core/AudioConverter.cpp +130 -0
- torchcodec/_core/AudioConverter.h +59 -0
- torchcodec/_core/BetaCudaDeviceInterface.cpp +1635 -0
- torchcodec/_core/BetaCudaDeviceInterface.h +364 -0
- torchcodec/_core/CMakeLists.txt +661 -0
- torchcodec/_core/CUDACommon.cpp +129 -0
- torchcodec/_core/CUDACommon.h +115 -0
- torchcodec/_core/Cache.h +126 -0
- torchcodec/_core/CodecParameters.cpp +98 -0
- torchcodec/_core/CodecParameters.h +59 -0
- torchcodec/_core/ColorConverter.cpp +92 -0
- torchcodec/_core/ColorConverter.h +40 -0
- torchcodec/_core/CpuDeviceInterface.cpp +654 -0
- torchcodec/_core/CpuDeviceInterface.h +153 -0
- torchcodec/_core/CudaDeviceInterface.cpp +519 -0
- torchcodec/_core/CudaDeviceInterface.h +92 -0
- torchcodec/_core/DecodeAvif.cpp +284 -0
- torchcodec/_core/DecodeAvif.h +28 -0
- torchcodec/_core/DecodeGif.cpp +488 -0
- torchcodec/_core/DecodeGif.h +32 -0
- torchcodec/_core/DecodeHeic.cpp +306 -0
- torchcodec/_core/DecodeHeic.h +18 -0
- torchcodec/_core/DecodeJpeg.cpp +489 -0
- torchcodec/_core/DecodeJpeg.h +17 -0
- torchcodec/_core/DecodeJpegCuda.cpp +638 -0
- torchcodec/_core/DecodeJpegCuda.h +92 -0
- torchcodec/_core/DecodePng.cpp +569 -0
- torchcodec/_core/DecodePng.h +31 -0
- torchcodec/_core/DecodeWebp.cpp +238 -0
- torchcodec/_core/DecodeWebp.h +17 -0
- torchcodec/_core/Demuxer.cpp +415 -0
- torchcodec/_core/Demuxer.h +158 -0
- torchcodec/_core/DeviceInterface.cpp +152 -0
- torchcodec/_core/DeviceInterface.h +255 -0
- torchcodec/_core/EncodeJpeg.cpp +223 -0
- torchcodec/_core/EncodeJpeg.h +19 -0
- torchcodec/_core/EncodeJpegCuda.cpp +272 -0
- torchcodec/_core/EncodeJpegCuda.h +56 -0
- torchcodec/_core/EncodePng.cpp +207 -0
- torchcodec/_core/EncodePng.h +19 -0
- torchcodec/_core/Encoder.cpp +1023 -0
- torchcodec/_core/Encoder.h +144 -0
- torchcodec/_core/Exif.h +241 -0
- torchcodec/_core/FFMPEGCommon.cpp +1159 -0
- torchcodec/_core/FFMPEGCommon.h +506 -0
- torchcodec/_core/FileIO.cpp +78 -0
- torchcodec/_core/FileIO.h +34 -0
- torchcodec/_core/FileLikeIO.cpp +76 -0
- torchcodec/_core/FileLikeIO.h +68 -0
- torchcodec/_core/FilterGraph.cpp +211 -0
- torchcodec/_core/FilterGraph.h +59 -0
- torchcodec/_core/Frame.cpp +75 -0
- torchcodec/_core/Frame.h +76 -0
- torchcodec/_core/IOInterface.h +44 -0
- torchcodec/_core/ImageCommon.h +113 -0
- torchcodec/_core/Logging.cpp +42 -0
- torchcodec/_core/Logging.h +38 -0
- torchcodec/_core/Metadata.cpp +312 -0
- torchcodec/_core/Metadata.h +115 -0
- torchcodec/_core/NVCUVIDRuntimeLoader.cpp +324 -0
- torchcodec/_core/NVCUVIDRuntimeLoader.h +14 -0
- torchcodec/_core/NVDECCache.cpp +111 -0
- torchcodec/_core/NVDECCache.h +136 -0
- torchcodec/_core/NVDECCacheConfig.cpp +61 -0
- torchcodec/_core/NVDECCacheConfig.h +30 -0
- torchcodec/_core/PacketDecoder.cpp +358 -0
- torchcodec/_core/PacketDecoder.h +140 -0
- torchcodec/_core/SingleStreamDecoder.cpp +1856 -0
- torchcodec/_core/SingleStreamDecoder.h +424 -0
- torchcodec/_core/StableABICompat.h +213 -0
- torchcodec/_core/StreamOptions.h +93 -0
- torchcodec/_core/SwScale.cpp +124 -0
- torchcodec/_core/SwScale.h +67 -0
- torchcodec/_core/TensorIO.cpp +136 -0
- torchcodec/_core/TensorIO.h +53 -0
- torchcodec/_core/Transform.cpp +207 -0
- torchcodec/_core/Transform.h +125 -0
- torchcodec/_core/ValidationUtils.cpp +65 -0
- torchcodec/_core/ValidationUtils.h +29 -0
- torchcodec/_core/WavDecoder.cpp +494 -0
- torchcodec/_core/WavDecoder.h +73 -0
- torchcodec/_core/__init__.py +45 -0
- torchcodec/_core/_decoder_utils.py +258 -0
- torchcodec/_core/_ffmpeg_op_names.py +95 -0
- torchcodec/_core/_ffmpeg_ops.py +699 -0
- torchcodec/_core/_file_like.py +221 -0
- torchcodec/_core/_metadata.py +402 -0
- torchcodec/_core/color_conversion.cpp +316 -0
- torchcodec/_core/color_conversion.cu +391 -0
- torchcodec/_core/color_conversion.h +150 -0
- torchcodec/_core/custom_ops.cpp +2438 -0
- torchcodec/_core/fetch_and_expose_non_gpl_ffmpeg_libs.cmake +192 -0
- torchcodec/_core/fetch_avif_from_s3.cmake +81 -0
- torchcodec/_core/giflib/README +28 -0
- torchcodec/_core/giflib/dgif_lib.c +1313 -0
- torchcodec/_core/giflib/gif_hash.c +129 -0
- torchcodec/_core/giflib/gif_hash.h +43 -0
- torchcodec/_core/giflib/gif_lib.h +292 -0
- torchcodec/_core/giflib/gif_lib_private.h +73 -0
- torchcodec/_core/giflib/gifalloc.c +426 -0
- torchcodec/_core/giflib/openbsd-reallocarray.c +74 -0
- torchcodec/_core/heic_custom_ops.cpp +20 -0
- torchcodec/_core/image_custom_ops.cpp +137 -0
- torchcodec/_core/nvcuvid_include/cuviddec.h +1374 -0
- torchcodec/_core/nvcuvid_include/nvcuvid.h +610 -0
- torchcodec/_core/ops.py +103 -0
- torchcodec/_core/sources.bzl +113 -0
- torchcodec/_frame.py +146 -0
- torchcodec/_internally_replaced_utils.py +129 -0
- torchcodec/_logging.py +59 -0
- torchcodec/decoders/__init__.py +50 -0
- torchcodec/decoders/_audio_decoder.py +183 -0
- torchcodec/decoders/_blocks/__init__.py +48 -0
- torchcodec/decoders/_blocks/_audio_converter.py +155 -0
- torchcodec/decoders/_blocks/_codec_parameters.py +229 -0
- torchcodec/decoders/_blocks/_color_converter.py +107 -0
- torchcodec/decoders/_blocks/_demuxer.py +678 -0
- torchcodec/decoders/_blocks/_frame.py +577 -0
- torchcodec/decoders/_blocks/_helpers.py +53 -0
- torchcodec/decoders/_blocks/_packet_decoder.py +357 -0
- torchcodec/decoders/_decoder_utils.py +128 -0
- torchcodec/decoders/_image_decoders.py +1575 -0
- torchcodec/decoders/_video_decoder.py +592 -0
- torchcodec/decoders/_wav_decoder.py +131 -0
- torchcodec/encoders/__init__.py +4 -0
- torchcodec/encoders/_audio_encoder.py +167 -0
- torchcodec/encoders/_image_encoders.py +181 -0
- torchcodec/encoders/_multi_stream_encoder.py +272 -0
- torchcodec/encoders/_video_encoder.py +227 -0
- torchcodec/jpeg8.dll +0 -0
- torchcodec/libavif.dll +0 -0
- torchcodec/libpng16.dll +0 -0
- torchcodec/libsharpyuv.dll +0 -0
- torchcodec/libtorchcodec_core4.dll +0 -0
- torchcodec/libtorchcodec_core5.dll +0 -0
- torchcodec/libtorchcodec_core6.dll +0 -0
- torchcodec/libtorchcodec_core7.dll +0 -0
- torchcodec/libtorchcodec_core8.dll +0 -0
- torchcodec/libtorchcodec_core9.dll +0 -0
- torchcodec/libtorchcodec_custom_ops4.dll +0 -0
- torchcodec/libtorchcodec_custom_ops5.dll +0 -0
- torchcodec/libtorchcodec_custom_ops6.dll +0 -0
- torchcodec/libtorchcodec_custom_ops7.dll +0 -0
- torchcodec/libtorchcodec_custom_ops8.dll +0 -0
- torchcodec/libtorchcodec_custom_ops9.dll +0 -0
- torchcodec/libtorchcodec_heic.dll +0 -0
- torchcodec/libtorchcodec_image.dll +0 -0
- torchcodec/libwebp.dll +0 -0
- torchcodec/libwebpdecoder.dll +0 -0
- torchcodec/libwebpdemux.dll +0 -0
- torchcodec/libwebpmux.dll +0 -0
- torchcodec/libzstd.dll +0 -0
- torchcodec/py.typed +0 -0
- torchcodec/samplers/__init__.py +2 -0
- torchcodec/samplers/_common.py +83 -0
- torchcodec/samplers/_index_based.py +287 -0
- torchcodec/samplers/_time_based.py +360 -0
- torchcodec/share/cmake/TorchCodec/TorchCodecConfig.cmake +76 -0
- torchcodec/share/cmake/TorchCodec/ffmpeg_versions.cmake +128 -0
- torchcodec/transforms/__init__.py +12 -0
- torchcodec/transforms/_decoder_transforms.py +375 -0
- torchcodec/version.py +1 -0
- torchcodec/zlib.dll +0 -0
- torchcodec-1.0.0.dist-info/METADATA +275 -0
- torchcodec-1.0.0.dist-info/RECORD +179 -0
- torchcodec-1.0.0.dist-info/WHEEL +5 -0
- torchcodec-1.0.0.dist-info/licenses/LICENSE +28 -0
- torchcodec-1.0.0.dist-info/licenses/third_party/COPYING.dav1d +23 -0
- torchcodec-1.0.0.dist-info/licenses/third_party/LICENSE.libavif +387 -0
- torchcodec-1.0.0.dist-info/licenses/third_party/LICENSE.libjpeg-turbo +135 -0
- torchcodec-1.0.0.dist-info/licenses/third_party/LICENSE.libpng +134 -0
- torchcodec-1.0.0.dist-info/licenses/third_party/LICENSE.libwebp +30 -0
- torchcodec-1.0.0.dist-info/licenses/third_party/LICENSE.libyuv +29 -0
- torchcodec-1.0.0.dist-info/licenses/third_party/LICENSE.zlib +22 -0
|
@@ -0,0 +1,183 @@
|
|
|
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 math
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
|
|
12
|
+
import torch
|
|
13
|
+
from torch import Tensor
|
|
14
|
+
|
|
15
|
+
from torchcodec import _core as core, AudioSamples
|
|
16
|
+
from torchcodec._core._decoder_utils import create_audio_decoder
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class AudioDecoder:
|
|
20
|
+
"""A single-stream audio decoder.
|
|
21
|
+
|
|
22
|
+
This can be used to decode audio from pure audio files (e.g. mp3, wav,
|
|
23
|
+
etc.), or from videos that contain audio streams (e.g. mp4 videos).
|
|
24
|
+
|
|
25
|
+
.. tip::
|
|
26
|
+
|
|
27
|
+
If you are decoding WAV files, consider using
|
|
28
|
+
:class:`~torchcodec.decoders.WavDecoder` instead for significantly faster
|
|
29
|
+
decoding.
|
|
30
|
+
|
|
31
|
+
Returned samples are float samples normalized in [-1, 1]
|
|
32
|
+
|
|
33
|
+
Args:
|
|
34
|
+
source (str, ``Pathlib.path``, bytes, ``torch.Tensor`` or file-like
|
|
35
|
+
object): The source of the video or audio:
|
|
36
|
+
|
|
37
|
+
- If ``str``: a local path or a URL to a video or audio file.
|
|
38
|
+
- If ``Pathlib.path``: a path to a local video or audio file.
|
|
39
|
+
- If ``bytes`` object or ``torch.Tensor``: the raw encoded audio data.
|
|
40
|
+
- If file-like object: we read video data from the object on demand. The object must
|
|
41
|
+
expose the methods `read(self, size: int) -> bytes` and
|
|
42
|
+
`seek(self, offset: int, whence: int) -> int`. Read more in:
|
|
43
|
+
:ref:`sphx_glr_generated_examples_decoding_file_like.py`.
|
|
44
|
+
stream_index (int, optional): Specifies which stream in the file to decode samples from.
|
|
45
|
+
Note that this index is absolute across all media types. If left unspecified, then
|
|
46
|
+
the :term:`best stream` is used.
|
|
47
|
+
sample_rate (int, optional): The desired output sample rate of the decoded samples.
|
|
48
|
+
By default, the sample rate of the source is used.
|
|
49
|
+
num_channels (int, optional): The desired number of channels of the decoded samples.
|
|
50
|
+
By default, the number of channels of the source is used.
|
|
51
|
+
|
|
52
|
+
Attributes:
|
|
53
|
+
metadata (AudioStreamMetadata): Metadata of the audio stream.
|
|
54
|
+
stream_index (int): The stream index that this decoder is retrieving samples from. If a
|
|
55
|
+
stream index was provided at initialization, this is the same value. If it was left
|
|
56
|
+
unspecified, this is the :term:`best stream`.
|
|
57
|
+
"""
|
|
58
|
+
|
|
59
|
+
def __init__(
|
|
60
|
+
self,
|
|
61
|
+
source: str | Path | io.RawIOBase | io.BufferedReader | bytes | Tensor,
|
|
62
|
+
*,
|
|
63
|
+
stream_index: int | None = None,
|
|
64
|
+
sample_rate: int | None = None,
|
|
65
|
+
num_channels: int | None = None,
|
|
66
|
+
):
|
|
67
|
+
torch._C._log_api_usage_once("torchcodec.decoders.AudioDecoder")
|
|
68
|
+
|
|
69
|
+
(
|
|
70
|
+
self._decoder,
|
|
71
|
+
self.stream_index,
|
|
72
|
+
self.metadata,
|
|
73
|
+
) = create_audio_decoder(
|
|
74
|
+
source=source,
|
|
75
|
+
seek_mode="approximate",
|
|
76
|
+
stream_index=stream_index,
|
|
77
|
+
sample_rate=sample_rate,
|
|
78
|
+
num_channels=num_channels,
|
|
79
|
+
)
|
|
80
|
+
|
|
81
|
+
self._desired_sample_rate = (
|
|
82
|
+
sample_rate if sample_rate is not None else self.metadata.sample_rate
|
|
83
|
+
)
|
|
84
|
+
|
|
85
|
+
def get_all_samples(self) -> AudioSamples:
|
|
86
|
+
"""Returns all the audio samples from the source.
|
|
87
|
+
|
|
88
|
+
To decode samples in a specific range, use
|
|
89
|
+
:meth:`~torchcodec.decoders.AudioDecoder.get_samples_played_in_range`.
|
|
90
|
+
|
|
91
|
+
Returns:
|
|
92
|
+
AudioSamples: The samples within the file.
|
|
93
|
+
"""
|
|
94
|
+
return self.get_samples_played_in_range()
|
|
95
|
+
|
|
96
|
+
def get_samples_played_in_range(
|
|
97
|
+
self, start_seconds: float = 0.0, stop_seconds: float | None = None
|
|
98
|
+
) -> AudioSamples:
|
|
99
|
+
"""Returns audio samples in the given range.
|
|
100
|
+
|
|
101
|
+
Samples are in the half open range [start_seconds, stop_seconds).
|
|
102
|
+
|
|
103
|
+
To decode all the samples from beginning to end, you can call this
|
|
104
|
+
method while leaving ``start_seconds`` and ``stop_seconds`` to their
|
|
105
|
+
default values, or use
|
|
106
|
+
:meth:`~torchcodec.decoders.AudioDecoder.get_all_samples` as a more
|
|
107
|
+
convenient alias.
|
|
108
|
+
|
|
109
|
+
Args:
|
|
110
|
+
start_seconds (float): Time, in seconds, of the start of the
|
|
111
|
+
range. Default: 0.
|
|
112
|
+
stop_seconds (float or None): Time, in seconds, of the end of the
|
|
113
|
+
range. As a half open range, the end is excluded. Default: None,
|
|
114
|
+
which decodes samples until the end.
|
|
115
|
+
|
|
116
|
+
Returns:
|
|
117
|
+
AudioSamples: The samples within the specified range.
|
|
118
|
+
"""
|
|
119
|
+
if stop_seconds is not None and not start_seconds <= stop_seconds:
|
|
120
|
+
raise ValueError(
|
|
121
|
+
f"Invalid start seconds: {start_seconds}. It must be less than or equal to stop seconds ({stop_seconds})."
|
|
122
|
+
)
|
|
123
|
+
frames, first_pts = core.get_frames_by_pts_in_range_audio(
|
|
124
|
+
self._decoder,
|
|
125
|
+
start_seconds=start_seconds,
|
|
126
|
+
stop_seconds=stop_seconds,
|
|
127
|
+
)
|
|
128
|
+
first_pts = first_pts.item()
|
|
129
|
+
|
|
130
|
+
# x = frame boundaries
|
|
131
|
+
#
|
|
132
|
+
# first_pts last_pts
|
|
133
|
+
# v v
|
|
134
|
+
# ....x..........x..........x...........x..........x..........x.....
|
|
135
|
+
# ^ ^
|
|
136
|
+
# start_seconds stop_seconds
|
|
137
|
+
#
|
|
138
|
+
# We want to return the samples in [start_seconds, stop_seconds). But
|
|
139
|
+
# because the core API is based on frames, the `frames` tensor contains
|
|
140
|
+
# the samples in [first_pts, last_pts)
|
|
141
|
+
# So we do some basic math to figure out the position of the view that
|
|
142
|
+
# we'll return.
|
|
143
|
+
|
|
144
|
+
sample_rate = self._desired_sample_rate
|
|
145
|
+
# TODO: metadata's sample_rate should probably not be Optional
|
|
146
|
+
assert sample_rate is not None # mypy.
|
|
147
|
+
|
|
148
|
+
stream_start = self.metadata.begin_stream_seconds_from_header or 0.0
|
|
149
|
+
|
|
150
|
+
def offset_of(seconds: float) -> int:
|
|
151
|
+
# This is morally equivalent to round((seconds - first_pts) *
|
|
152
|
+
# sample_rate), but a given `seconds` must map to the same sample
|
|
153
|
+
# across calls, whatever the value of `first_pts`.
|
|
154
|
+
# The non-regression tests for this are
|
|
155
|
+
# test_chunk_boundary_half_sample and
|
|
156
|
+
# test_chunk_boundary_half_sample_after_frame_start
|
|
157
|
+
seconds_index = math.floor((seconds - stream_start) * sample_rate + 0.5)
|
|
158
|
+
first_pts_index = math.floor((first_pts - stream_start) * sample_rate + 0.5)
|
|
159
|
+
return seconds_index - first_pts_index
|
|
160
|
+
|
|
161
|
+
if first_pts < start_seconds:
|
|
162
|
+
offset_beginning = offset_of(start_seconds)
|
|
163
|
+
output_pts_seconds = start_seconds
|
|
164
|
+
else:
|
|
165
|
+
# In normal cases we'll have first_pts <= start_pts, but in some
|
|
166
|
+
# edge cases it's possible to have first_pts > start_seconds,
|
|
167
|
+
# typically if the stream's first frame's pts isn't exactly 0.
|
|
168
|
+
offset_beginning = 0
|
|
169
|
+
output_pts_seconds = first_pts
|
|
170
|
+
|
|
171
|
+
num_samples = frames.shape[1]
|
|
172
|
+
if stop_seconds is not None:
|
|
173
|
+
offset_end = min(num_samples, offset_of(stop_seconds))
|
|
174
|
+
else:
|
|
175
|
+
offset_end = num_samples
|
|
176
|
+
|
|
177
|
+
data = frames[:, offset_beginning:offset_end]
|
|
178
|
+
return AudioSamples(
|
|
179
|
+
data=data,
|
|
180
|
+
pts_seconds=output_pts_seconds,
|
|
181
|
+
duration_seconds=data.shape[1] / sample_rate,
|
|
182
|
+
sample_rate=sample_rate,
|
|
183
|
+
)
|
|
@@ -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
|
+
from torchcodec._core._metadata import (
|
|
8
|
+
AudioStreamHeaderMetadata,
|
|
9
|
+
ContainerMetadata,
|
|
10
|
+
DemuxerMetadata,
|
|
11
|
+
StreamMetadata,
|
|
12
|
+
VideoStreamHeaderMetadata,
|
|
13
|
+
)
|
|
14
|
+
|
|
15
|
+
from ._audio_converter import AudioConverter
|
|
16
|
+
from ._codec_parameters import AudioCodecParameters, VideoCodecParameters
|
|
17
|
+
from ._color_converter import ColorConverter
|
|
18
|
+
from ._demuxer import (
|
|
19
|
+
AudioStream,
|
|
20
|
+
Demuxer,
|
|
21
|
+
FrameIndex,
|
|
22
|
+
get_container_metadata,
|
|
23
|
+
VideoStream,
|
|
24
|
+
)
|
|
25
|
+
from ._frame import Packet, RawAudioSamples, RawFrame
|
|
26
|
+
from ._packet_decoder import AudioPacketDecoder, VideoPacketDecoder
|
|
27
|
+
|
|
28
|
+
__all__ = [
|
|
29
|
+
"Demuxer",
|
|
30
|
+
"get_container_metadata",
|
|
31
|
+
"VideoStream",
|
|
32
|
+
"AudioStream",
|
|
33
|
+
"VideoCodecParameters",
|
|
34
|
+
"AudioCodecParameters",
|
|
35
|
+
"VideoPacketDecoder",
|
|
36
|
+
"AudioPacketDecoder",
|
|
37
|
+
"ColorConverter",
|
|
38
|
+
"AudioConverter",
|
|
39
|
+
"Packet",
|
|
40
|
+
"RawFrame",
|
|
41
|
+
"RawAudioSamples",
|
|
42
|
+
"FrameIndex",
|
|
43
|
+
"DemuxerMetadata",
|
|
44
|
+
"ContainerMetadata",
|
|
45
|
+
"StreamMetadata",
|
|
46
|
+
"VideoStreamHeaderMetadata",
|
|
47
|
+
"AudioStreamHeaderMetadata",
|
|
48
|
+
]
|
|
@@ -0,0 +1,155 @@
|
|
|
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
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from torchcodec._core.ops import (
|
|
10
|
+
_blocks_audio_converter_convert,
|
|
11
|
+
_blocks_audio_converter_drain,
|
|
12
|
+
_blocks_audio_converter_reset,
|
|
13
|
+
_blocks_create_audio_converter,
|
|
14
|
+
)
|
|
15
|
+
from torchcodec._frame import AudioSamples
|
|
16
|
+
|
|
17
|
+
from ._frame import RawAudioSamples
|
|
18
|
+
from ._helpers import _process_local
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@_process_local(
|
|
22
|
+
"A resampler carries filter history across calls that FFmpeg cannot "
|
|
23
|
+
"serialise. Construct one in each process."
|
|
24
|
+
)
|
|
25
|
+
class AudioConverter:
|
|
26
|
+
"""Turn :class:`RawAudioSamples` into normalised float32
|
|
27
|
+
:class:`~torchcodec.AudioSamples`, optionally resampling and remixing
|
|
28
|
+
channels.
|
|
29
|
+
|
|
30
|
+
This is a low-level API: for straightforward decoding, use
|
|
31
|
+
:class:`~torchcodec.decoders.AudioDecoder` instead.
|
|
32
|
+
|
|
33
|
+
.. code-block:: python
|
|
34
|
+
|
|
35
|
+
converter = AudioConverter(sample_rate=16_000)
|
|
36
|
+
|
|
37
|
+
for packet in demuxer:
|
|
38
|
+
for raw_samples in packet_decoder.decode(packet):
|
|
39
|
+
samples = converter.convert(raw_samples)
|
|
40
|
+
for raw_samples in packet_decoder.drain():
|
|
41
|
+
samples = converter.convert(raw_samples)
|
|
42
|
+
samples = converter.drain()
|
|
43
|
+
|
|
44
|
+
Unlike a :class:`ColorConverter`, this object is a stateful stream
|
|
45
|
+
processor, and it is bound to an audio stream: feed it the stream's samples
|
|
46
|
+
in order. When resampling, it holds samples back between calls, so you won't
|
|
47
|
+
necessarily get the same number of samples out as you put in for a given
|
|
48
|
+
call to :meth:`convert`.
|
|
49
|
+
|
|
50
|
+
Args:
|
|
51
|
+
sample_rate (int, optional): The output sample rate. Defaults to the
|
|
52
|
+
source's own, i.e. no resampling.
|
|
53
|
+
num_channels (int, optional): The output number of channels. Defaults
|
|
54
|
+
to the source's own.
|
|
55
|
+
"""
|
|
56
|
+
|
|
57
|
+
def __init__(self, sample_rate: int | None = None, num_channels: int | None = None):
|
|
58
|
+
self._handle = _blocks_create_audio_converter(
|
|
59
|
+
sample_rate=sample_rate, num_channels=num_channels
|
|
60
|
+
)
|
|
61
|
+
self._requested_sample_rate = sample_rate
|
|
62
|
+
self._drained = False
|
|
63
|
+
|
|
64
|
+
self._first_frame_pts_seconds: float | None = None
|
|
65
|
+
self._out_sample_rate: int | None = None
|
|
66
|
+
self._num_emitted_samples = 0
|
|
67
|
+
# The demuxer position these samples come from. See Packet._generation:
|
|
68
|
+
# a resampler carries state across calls, so a seek invalidates it just
|
|
69
|
+
# as it invalidates the decoder's.
|
|
70
|
+
self._generation: int | None = None
|
|
71
|
+
|
|
72
|
+
def _wrap(self, data) -> AudioSamples:
|
|
73
|
+
assert self._out_sample_rate is not None # mypy
|
|
74
|
+
assert self._first_frame_pts_seconds is not None # mypy
|
|
75
|
+
# We manually compute the pts of all frames but the first one: when
|
|
76
|
+
# resampling happens, libswresample buffers samples and emits them
|
|
77
|
+
# later. Not all the samples of the first frame are necessarily emitted
|
|
78
|
+
# immediately, they may be emitted with the next frame. Without this,
|
|
79
|
+
# we'd fail the test_audio_converter_pts_is_contiguous() test.
|
|
80
|
+
pts_seconds = (
|
|
81
|
+
self._first_frame_pts_seconds
|
|
82
|
+
+ self._num_emitted_samples / self._out_sample_rate
|
|
83
|
+
)
|
|
84
|
+
self._num_emitted_samples += data.shape[1]
|
|
85
|
+
return AudioSamples(
|
|
86
|
+
data=data,
|
|
87
|
+
pts_seconds=pts_seconds,
|
|
88
|
+
duration_seconds=data.shape[1] / self._out_sample_rate,
|
|
89
|
+
sample_rate=self._out_sample_rate,
|
|
90
|
+
)
|
|
91
|
+
|
|
92
|
+
def convert(self, raw_samples: RawAudioSamples) -> AudioSamples:
|
|
93
|
+
"""Convert one :class:`RawAudioSamples` into normalised float32
|
|
94
|
+
:class:`~torchcodec.AudioSamples`.
|
|
95
|
+
|
|
96
|
+
You may not get the same number of samples out as you put in, especially
|
|
97
|
+
if you are resampling.
|
|
98
|
+
|
|
99
|
+
Returns:
|
|
100
|
+
The converted samples, normalised float32 in ``[-1, 1]``. When
|
|
101
|
+
resampling, fewer than were passed in, possibly none.
|
|
102
|
+
"""
|
|
103
|
+
if self._generation is None:
|
|
104
|
+
self._generation = raw_samples._generation
|
|
105
|
+
elif self._generation != raw_samples._generation:
|
|
106
|
+
raise RuntimeError(
|
|
107
|
+
"The demuxer seeked since this converter was last reset(), and "
|
|
108
|
+
"a resampler carries state across calls, so these samples "
|
|
109
|
+
"would be resampled against the wrong history. Call reset() on "
|
|
110
|
+
"every converter fed by that demuxer after a seek."
|
|
111
|
+
)
|
|
112
|
+
if self._drained:
|
|
113
|
+
raise RuntimeError(
|
|
114
|
+
"This AudioConverter has been drained. Call reset() to convert "
|
|
115
|
+
"more samples."
|
|
116
|
+
)
|
|
117
|
+
if self._first_frame_pts_seconds is None:
|
|
118
|
+
self._first_frame_pts_seconds = raw_samples.pts_seconds
|
|
119
|
+
self._out_sample_rate = (
|
|
120
|
+
self._requested_sample_rate
|
|
121
|
+
if self._requested_sample_rate is not None
|
|
122
|
+
else raw_samples.sample_rate
|
|
123
|
+
)
|
|
124
|
+
data = _blocks_audio_converter_convert(
|
|
125
|
+
self._handle, raw_samples.data, raw_samples.sample_rate
|
|
126
|
+
)
|
|
127
|
+
return self._wrap(data)
|
|
128
|
+
|
|
129
|
+
def drain(self) -> AudioSamples:
|
|
130
|
+
"""Return the samples the resampler was still holding on to.
|
|
131
|
+
|
|
132
|
+
Empty unless you are resampling. This is not the codec's own buffer,
|
|
133
|
+
which :meth:`AudioPacketDecoder.drain` takes care of.
|
|
134
|
+
"""
|
|
135
|
+
if self._first_frame_pts_seconds is None:
|
|
136
|
+
raise RuntimeError(
|
|
137
|
+
"This AudioConverter hasn't converted any samples, so there is "
|
|
138
|
+
"nothing to drain."
|
|
139
|
+
)
|
|
140
|
+
data = _blocks_audio_converter_drain(self._handle)
|
|
141
|
+
self._drained = True
|
|
142
|
+
return self._wrap(data)
|
|
143
|
+
|
|
144
|
+
def reset(self) -> None:
|
|
145
|
+
"""Drop the resampler's state and start over.
|
|
146
|
+
|
|
147
|
+
Needed after a :meth:`Demuxer.seek`, after :meth:`drain`, and before
|
|
148
|
+
converting a different stream.
|
|
149
|
+
"""
|
|
150
|
+
_blocks_audio_converter_reset(self._handle)
|
|
151
|
+
self._drained = False
|
|
152
|
+
self._first_frame_pts_seconds = None
|
|
153
|
+
self._out_sample_rate = None
|
|
154
|
+
self._generation = None
|
|
155
|
+
self._num_emitted_samples = 0
|
|
@@ -0,0 +1,229 @@
|
|
|
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
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import dataclasses
|
|
10
|
+
from dataclasses import dataclass, field, KW_ONLY
|
|
11
|
+
from fractions import Fraction
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _check_fraction(name: str, value: object) -> None:
|
|
15
|
+
if not isinstance(value, Fraction):
|
|
16
|
+
raise ValueError(f"{name} must be a Fraction, got {value!r}.")
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _short_repr(value: object) -> str:
|
|
20
|
+
if isinstance(value, bytes):
|
|
21
|
+
return f"<{len(value)} bytes>"
|
|
22
|
+
if isinstance(value, dict):
|
|
23
|
+
entries = ", ".join(f"{k!r}: {_short_repr(v)}" for k, v in value.items())
|
|
24
|
+
return "{" + entries + "}"
|
|
25
|
+
return repr(value)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@dataclass(frozen=True, repr=False)
|
|
29
|
+
class _CodecParameters:
|
|
30
|
+
codec: str
|
|
31
|
+
"""FFmpeg's name of the codec, e.g. ``"h264"``, ``"hevc"`` or ``"aac"``.
|
|
32
|
+
``ffmpeg -codecs`` lists them."""
|
|
33
|
+
_: KW_ONLY
|
|
34
|
+
time_base: Fraction
|
|
35
|
+
"""The unit of the packets' timestamps, in seconds: a packet's ``pts`` of
|
|
36
|
+
``n`` means ``n * time_base`` seconds."""
|
|
37
|
+
extradata: bytes | None = None
|
|
38
|
+
"""The codec's setup data that isn't in the packets, e.g. the ``avcC`` box
|
|
39
|
+
of H.264 in MP4. Not all codecs and streams need it."""
|
|
40
|
+
codec_tag: int | None = None
|
|
41
|
+
"""The container's identifier of the codec, e.g. a FourCC in AVI or MP4.
|
|
42
|
+
A few codecs read it to tell variants apart."""
|
|
43
|
+
profile: int | None = None
|
|
44
|
+
"""The codec's profile, as one of FFmpeg's ``AV_PROFILE_*`` values."""
|
|
45
|
+
level: int | None = None
|
|
46
|
+
"""The codec's level."""
|
|
47
|
+
bit_rate: int | None = None
|
|
48
|
+
"""The average bit rate, in bits per second."""
|
|
49
|
+
bits_per_coded_sample: int | None = None
|
|
50
|
+
"""The number of bits per sample in the compressed data, for the codecs
|
|
51
|
+
that need it (mostly uncompressed and PCM codecs)."""
|
|
52
|
+
bits_per_raw_sample: int | None = None
|
|
53
|
+
"""The number of bits per sample in the decoded data, when it's not implied
|
|
54
|
+
by the pixel or sample format, e.g. 10 for 10-bit video."""
|
|
55
|
+
coded_side_data: dict[str, bytes] | None = None
|
|
56
|
+
"""Extra data about the stream, keyed by FFmpeg's names for its types, e.g.
|
|
57
|
+
``"Display Matrix"`` for video or ``"Replay Gain"`` for audio.
|
|
58
|
+
|
|
59
|
+
If a video stream has a display matrix, it is under ``"Display Matrix"``
|
|
60
|
+
on every FFmpeg version."""
|
|
61
|
+
# FFmpeg's name of the format of the container the stream was demuxed from,
|
|
62
|
+
# e.g. "mpeg", or None when the parameters don't come from a Demuxer.
|
|
63
|
+
# Knowing the container lets the decoder keep behavior that is more accurate
|
|
64
|
+
# than what it can do without it: resyncing after a seek in an MPEG program
|
|
65
|
+
# stream, and picking NVDEC's bitstream filter. Without the container, the
|
|
66
|
+
# first packets after a seek in an MPEG program stream raise instead of
|
|
67
|
+
# being skipped (see
|
|
68
|
+
# test_mpeg_program_stream_resync_needs_the_container_format), which we
|
|
69
|
+
# expect to be rare. For NVDEC, we expect no difference in practice, but we
|
|
70
|
+
# keep the container to be safe. It survives pickling, but it's not part of
|
|
71
|
+
# the API.
|
|
72
|
+
_container_format_PRIVATE_DO_NOT_USE: str | None = field(
|
|
73
|
+
default=None, init=False, repr=False, compare=False
|
|
74
|
+
)
|
|
75
|
+
|
|
76
|
+
def __post_init__(self):
|
|
77
|
+
if not isinstance(self.codec, str) or not self.codec:
|
|
78
|
+
raise ValueError(f"codec must be a non-empty string, got {self.codec!r}.")
|
|
79
|
+
_check_fraction("time_base", self.time_base)
|
|
80
|
+
if self.time_base <= 0:
|
|
81
|
+
raise ValueError(f"time_base must be positive, got {self.time_base}.")
|
|
82
|
+
|
|
83
|
+
def __repr__(self) -> str:
|
|
84
|
+
fields = ", ".join(
|
|
85
|
+
f"{f.name}={_short_repr(getattr(self, f.name))}"
|
|
86
|
+
for f in dataclasses.fields(self)
|
|
87
|
+
if f.repr and getattr(self, f.name) is not None
|
|
88
|
+
)
|
|
89
|
+
return f"{type(self).__name__}({fields})"
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
@dataclass(frozen=True, repr=False, kw_only=True)
|
|
93
|
+
class VideoCodecParameters(_CodecParameters):
|
|
94
|
+
"""What a :class:`VideoPacketDecoder` needs to know to decode the packets
|
|
95
|
+
of a video stream.
|
|
96
|
+
|
|
97
|
+
If you have a :class:`Demuxer`, :attr:`VideoStream.codec_parameters` gives
|
|
98
|
+
you the parameters of a stream. They can be pickled, e.g. to build the
|
|
99
|
+
decoder in another process. To decode packets that don't come from a
|
|
100
|
+
``Demuxer``, build them yourself::
|
|
101
|
+
|
|
102
|
+
codec_parameters = VideoCodecParameters(
|
|
103
|
+
"h264", time_base=Fraction(1, 90_000), extradata=extradata
|
|
104
|
+
)
|
|
105
|
+
decoder = VideoPacketDecoder(codec_parameters)
|
|
106
|
+
|
|
107
|
+
The fields mirror those of FFmpeg's `AVCodecParameters
|
|
108
|
+
<https://ffmpeg.org/doxygen/trunk/structAVCodecParameters.html>`_, with the
|
|
109
|
+
same names and meanings. FFmpeg's names stand for its enums, e.g.
|
|
110
|
+
``pixel_format="yuv420p"``.
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
.. note::
|
|
114
|
+
|
|
115
|
+
Which fields you need depends on the codec and device: printing the parameters a
|
|
116
|
+
``Demuxer`` reports for a similar file shows what FFmpeg uses.
|
|
117
|
+
|
|
118
|
+
To decode on CUDA, set ``width``, ``height`` and ``pixel_format``:
|
|
119
|
+
depending on the codec, the frames may otherwise be silently decoded
|
|
120
|
+
on the CPU. Also set ``r_frame_rate``, or the frames' durations are 0.
|
|
121
|
+
|
|
122
|
+
.. note::
|
|
123
|
+
|
|
124
|
+
The parameters are meant to be passed to a decoder or stored, not read
|
|
125
|
+
as metadata: use :attr:`VideoStream.metadata` for that. The values a
|
|
126
|
+
``Demuxer`` reports are FFmpeg's, and can change across FFmpeg and
|
|
127
|
+
TorchCodec versions. The fields' names and meanings are stable.
|
|
128
|
+
"""
|
|
129
|
+
|
|
130
|
+
width: int | None = None
|
|
131
|
+
"""The width of the frames, in pixels."""
|
|
132
|
+
height: int | None = None
|
|
133
|
+
"""The height of the frames, in pixels."""
|
|
134
|
+
pixel_format: str | None = None
|
|
135
|
+
"""FFmpeg's name of the decoded frames' pixel format, e.g. ``"yuv420p"``.
|
|
136
|
+
``ffmpeg -pix_fmts`` lists them."""
|
|
137
|
+
sample_aspect_ratio: Fraction | None = None
|
|
138
|
+
"""The width of a pixel divided by its height."""
|
|
139
|
+
framerate: Fraction | None = None
|
|
140
|
+
"""The frame rate, in frames per second, as the codec reports it. Setting
|
|
141
|
+
it requires FFmpeg 6.1 or above."""
|
|
142
|
+
r_frame_rate: Fraction | None = None
|
|
143
|
+
"""The frame rate, in frames per second, as the container reports it. Not
|
|
144
|
+
part of FFmpeg's ``AVCodecParameters``, but of its ``AVStream``."""
|
|
145
|
+
field_order: str | None = None
|
|
146
|
+
"""``"progressive"`` or, for interlaced video, which field comes first:
|
|
147
|
+
``"tt"``, ``"bb"``, ``"tb"`` or ``"bt"``."""
|
|
148
|
+
color_range: str | None = None
|
|
149
|
+
"""FFmpeg's name of the color range, e.g. ``"tv"`` (limited) or ``"pc"``
|
|
150
|
+
(full)."""
|
|
151
|
+
color_primaries: str | None = None
|
|
152
|
+
"""FFmpeg's name of the color primaries, e.g. ``"bt709"``."""
|
|
153
|
+
color_transfer_characteristic: str | None = None
|
|
154
|
+
"""FFmpeg's name of the transfer characteristic, e.g. ``"bt709"`` or
|
|
155
|
+
``"smpte2084"``."""
|
|
156
|
+
color_space: str | None = None
|
|
157
|
+
"""FFmpeg's name of the color space, i.e. the YUV matrix, e.g.
|
|
158
|
+
``"bt709"``."""
|
|
159
|
+
chroma_location: str | None = None
|
|
160
|
+
"""FFmpeg's name of the chroma samples' location, e.g. ``"left"``."""
|
|
161
|
+
video_delay: int | None = None
|
|
162
|
+
"""The number of frames the decoder holds back before it outputs one,
|
|
163
|
+
because of B-frames."""
|
|
164
|
+
|
|
165
|
+
def __post_init__(self):
|
|
166
|
+
super().__post_init__()
|
|
167
|
+
for name in ("sample_aspect_ratio", "framerate", "r_frame_rate"):
|
|
168
|
+
value = getattr(self, name)
|
|
169
|
+
if value is not None:
|
|
170
|
+
_check_fraction(name, value)
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
@dataclass(frozen=True, repr=False, kw_only=True)
|
|
174
|
+
class AudioCodecParameters(_CodecParameters):
|
|
175
|
+
"""What an :class:`AudioPacketDecoder` needs to know to decode the packets
|
|
176
|
+
of an audio stream.
|
|
177
|
+
|
|
178
|
+
If you have a :class:`Demuxer`, :attr:`AudioStream.codec_parameters` gives
|
|
179
|
+
you the parameters of a stream. They can be pickled, e.g. to build the
|
|
180
|
+
decoder in another process. To decode packets that don't come from a
|
|
181
|
+
``Demuxer``, build them yourself::
|
|
182
|
+
|
|
183
|
+
codec_parameters = AudioCodecParameters(
|
|
184
|
+
"aac",
|
|
185
|
+
time_base=Fraction(1, 48_000),
|
|
186
|
+
sample_rate=48_000,
|
|
187
|
+
channel_layout="stereo",
|
|
188
|
+
extradata=extradata,
|
|
189
|
+
)
|
|
190
|
+
decoder = AudioPacketDecoder(codec_parameters)
|
|
191
|
+
|
|
192
|
+
The fields mirror those of FFmpeg's `AVCodecParameters
|
|
193
|
+
<https://ffmpeg.org/doxygen/trunk/structAVCodecParameters.html>`_, with the
|
|
194
|
+
same names and meanings. FFmpeg's names stand for its enums, e.g.
|
|
195
|
+
``sample_format="fltp"``.
|
|
196
|
+
|
|
197
|
+
Which fields you need depends on the codec: printing the parameters a
|
|
198
|
+
``Demuxer`` reports for a similar file shows what FFmpeg uses.
|
|
199
|
+
|
|
200
|
+
.. note::
|
|
201
|
+
|
|
202
|
+
The parameters are meant to be passed to a decoder or stored, not read
|
|
203
|
+
as metadata: use :attr:`AudioStream.metadata` for that. The values a
|
|
204
|
+
``Demuxer`` reports are FFmpeg's, and can change across FFmpeg and
|
|
205
|
+
TorchCodec versions. The fields' names and meanings are stable.
|
|
206
|
+
"""
|
|
207
|
+
|
|
208
|
+
sample_format: str | None = None
|
|
209
|
+
"""FFmpeg's name of the decoded samples' format, e.g. ``"fltp"``.
|
|
210
|
+
``ffmpeg -sample_fmts`` lists them."""
|
|
211
|
+
sample_rate: int | None = None
|
|
212
|
+
"""The sample rate, in Hz."""
|
|
213
|
+
channel_layout: str | None = None
|
|
214
|
+
"""FFmpeg's description of the channel layout, e.g. ``"stereo"`` or
|
|
215
|
+
``"5.1"``. ``ffmpeg -layouts`` lists them."""
|
|
216
|
+
block_align: int | None = None
|
|
217
|
+
"""The number of bytes per coded audio frame, for the codecs that need it
|
|
218
|
+
(e.g. PCM and ADPCM codecs)."""
|
|
219
|
+
frame_size: int | None = None
|
|
220
|
+
"""The number of samples per channel in a frame, for the codecs whose
|
|
221
|
+
frames all have the same size."""
|
|
222
|
+
initial_padding: int | None = None
|
|
223
|
+
"""The number of samples the encoder added at the start of the audio,
|
|
224
|
+
which aren't part of the original audio."""
|
|
225
|
+
trailing_padding: int | None = None
|
|
226
|
+
"""The number of samples the encoder added at the end of the audio, which
|
|
227
|
+
aren't part of the original audio."""
|
|
228
|
+
seek_preroll: int | None = None
|
|
229
|
+
"""The number of samples to skip after a discontinuity, e.g. a seek."""
|