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,272 @@
|
|
|
1
|
+
from pathlib import Path
|
|
2
|
+
from typing import Any
|
|
3
|
+
|
|
4
|
+
import torch
|
|
5
|
+
from torch import Tensor
|
|
6
|
+
|
|
7
|
+
from torchcodec import _core
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class VideoStream:
|
|
11
|
+
"""A video stream within an :class:`Encoder`.
|
|
12
|
+
|
|
13
|
+
Returned by :meth:`Encoder.add_video`. Use :meth:`add_frames` to feed
|
|
14
|
+
video frames into this stream.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
def __init__(self, encoder_tensor: Tensor, stream_identifier: int):
|
|
18
|
+
self._encoder_tensor = encoder_tensor
|
|
19
|
+
# This is a per-media-type index, not absolute across all media types,
|
|
20
|
+
# hence why we don't call this stream_index
|
|
21
|
+
self._stream_identifier = stream_identifier
|
|
22
|
+
|
|
23
|
+
def add_frames(self, frames: Tensor) -> None:
|
|
24
|
+
"""Add video frames to this stream.
|
|
25
|
+
|
|
26
|
+
Args:
|
|
27
|
+
frames (``torch.Tensor``): The frames to encode. This must be a 4D
|
|
28
|
+
tensor of shape ``(N, C, H, W)`` where N is the number of
|
|
29
|
+
frames, C is 3 channels (RGB), H is height, and W is width.
|
|
30
|
+
Values must be uint8 in the range ``[0, 255]``. The device of
|
|
31
|
+
the tensor must match the ``device`` passed to
|
|
32
|
+
:meth:`Encoder.add_video`.
|
|
33
|
+
"""
|
|
34
|
+
_core.streaming_encoder_add_frames(
|
|
35
|
+
self._encoder_tensor, frames, self._stream_identifier
|
|
36
|
+
)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class AudioStream:
|
|
40
|
+
"""An audio stream within an :class:`Encoder`.
|
|
41
|
+
|
|
42
|
+
Returned by :meth:`Encoder.add_audio`. Use :meth:`add_samples` to feed
|
|
43
|
+
audio samples into this stream.
|
|
44
|
+
"""
|
|
45
|
+
|
|
46
|
+
def __init__(self, encoder_tensor: Tensor, stream_identifier: int):
|
|
47
|
+
self._encoder_tensor = encoder_tensor
|
|
48
|
+
# This is a per-media-type index, not absolute across all media types,
|
|
49
|
+
# hence why we don't call this stream_index
|
|
50
|
+
self._stream_identifier = stream_identifier
|
|
51
|
+
|
|
52
|
+
def add_samples(self, samples: Tensor) -> None:
|
|
53
|
+
"""Add audio samples to this stream.
|
|
54
|
+
|
|
55
|
+
Args:
|
|
56
|
+
samples (``torch.Tensor``): The samples to encode. This must be a
|
|
57
|
+
2D tensor of shape ``(num_channels, num_samples)``. Values must
|
|
58
|
+
be float values in ``[-1, 1]``. The number of channels must
|
|
59
|
+
match the ``num_channels`` passed to :meth:`Encoder.add_audio`.
|
|
60
|
+
"""
|
|
61
|
+
_core.streaming_encoder_add_samples(
|
|
62
|
+
self._encoder_tensor, samples, self._stream_identifier
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
class Encoder:
|
|
67
|
+
"""A multi-stream encoder for encoding video and/or audio streams.
|
|
68
|
+
|
|
69
|
+
Unlike :class:`VideoEncoder` and :class:`AudioEncoder` which encode a
|
|
70
|
+
single stream in one shot, ``Encoder`` supports multiple streams and
|
|
71
|
+
incremental (streaming) encoding. Frames and samples can be added
|
|
72
|
+
progressively, which is useful when data is generated on-the-fly or when
|
|
73
|
+
encoding both audio and video into the same container.
|
|
74
|
+
|
|
75
|
+
Use :meth:`add_video` and :meth:`add_audio` to configure output streams,
|
|
76
|
+
then open an output destination with :meth:`open_file` or
|
|
77
|
+
:meth:`open_file_like`, feed data via the returned stream objects, and
|
|
78
|
+
finally call :meth:`close` (or use the encoder as a context manager).
|
|
79
|
+
|
|
80
|
+
Example:
|
|
81
|
+
|
|
82
|
+
.. code-block:: python
|
|
83
|
+
|
|
84
|
+
encoder = Encoder()
|
|
85
|
+
video_stream = encoder.add_video(height=256, width=256, frame_rate=30)
|
|
86
|
+
audio_stream = encoder.add_audio(sample_rate=16000, num_channels=1)
|
|
87
|
+
with encoder.open_file("output.mp4"):
|
|
88
|
+
video_stream.add_frames(frames_tensor)
|
|
89
|
+
audio_stream.add_samples(samples_tensor)
|
|
90
|
+
# Add more frames by calling video_stream.add_frames again
|
|
91
|
+
# Add more samples by calling audio_stream.add_samples again
|
|
92
|
+
|
|
93
|
+
To encode to a file-like object (e.g. ``io.BytesIO()``), use
|
|
94
|
+
:meth:`open_file_like` instead:
|
|
95
|
+
|
|
96
|
+
.. code-block:: python
|
|
97
|
+
|
|
98
|
+
import io
|
|
99
|
+
|
|
100
|
+
buf = io.BytesIO()
|
|
101
|
+
encoder = Encoder()
|
|
102
|
+
video_stream = encoder.add_video(height=256, width=256, frame_rate=30)
|
|
103
|
+
with encoder.open_file_like(buf, format="mp4"):
|
|
104
|
+
video_stream.add_frames(frames_tensor)
|
|
105
|
+
encoded_bytes = buf.getbuffer() # or getvalue()
|
|
106
|
+
# Optionally convert to a uint8 tensor of bytes with
|
|
107
|
+
# bytes_tensor = torch.frombuffer(encoded_bytes, dtype=torch.uint8)
|
|
108
|
+
"""
|
|
109
|
+
|
|
110
|
+
def __init__(self):
|
|
111
|
+
self._encoder_tensor = _core.create_streaming_encoder()
|
|
112
|
+
|
|
113
|
+
def add_video(
|
|
114
|
+
self,
|
|
115
|
+
*,
|
|
116
|
+
height: int,
|
|
117
|
+
width: int,
|
|
118
|
+
frame_rate: float,
|
|
119
|
+
device: str | torch.device | None = None,
|
|
120
|
+
codec: str | None = None,
|
|
121
|
+
pixel_format: str | None = None,
|
|
122
|
+
crf: int | float | None = None,
|
|
123
|
+
preset: str | int | None = None,
|
|
124
|
+
extra_options: dict[str, Any] | None = None,
|
|
125
|
+
) -> VideoStream:
|
|
126
|
+
"""Add a video stream to the encoder.
|
|
127
|
+
|
|
128
|
+
Must be called before :meth:`open_file` or :meth:`open_file_like`.
|
|
129
|
+
|
|
130
|
+
Args:
|
|
131
|
+
height (int): The height of the **input** video frames.
|
|
132
|
+
width (int): The width of the **input** video frames.
|
|
133
|
+
frame_rate (float): The frame rate of the **input** video frames.
|
|
134
|
+
Also defines the encoded **output** frame rate.
|
|
135
|
+
device (str or torch.device, optional): The device to use for
|
|
136
|
+
encoding, e.g. ``"cpu"`` or ``"cuda"``. If ``None`` (default), uses
|
|
137
|
+
the current default device.
|
|
138
|
+
codec (str, optional): The codec to use for encoding (e.g.,
|
|
139
|
+
``"libx264"``). If not specified, the default codec for the
|
|
140
|
+
container format will be used.
|
|
141
|
+
See :ref:`codec_selection` for details.
|
|
142
|
+
pixel_format (str, optional): The pixel format for encoding (e.g.,
|
|
143
|
+
``"yuv420p"``). If not specified, uses codec's default format.
|
|
144
|
+
Must be left as ``None`` when encoding on CUDA.
|
|
145
|
+
See :ref:`pixel_format` for details.
|
|
146
|
+
crf (int or float, optional): Constant Rate Factor for encoding
|
|
147
|
+
quality. Lower values mean better quality. Valid range depends
|
|
148
|
+
on the encoder (e.g. 0-51 for libx264). Defaults to None (which
|
|
149
|
+
will use encoder's default). See :ref:`crf` for details.
|
|
150
|
+
preset (str or int, optional): Encoder option that controls the
|
|
151
|
+
tradeoff between encoding speed and compression (output size).
|
|
152
|
+
Commonly a string: ``"fast"``, ``"medium"``, ``"slow"``.
|
|
153
|
+
Defaults to None (which will use encoder's default).
|
|
154
|
+
See :ref:`preset` for details.
|
|
155
|
+
extra_options (dict[str, Any], optional): A dictionary of additional
|
|
156
|
+
encoder options to pass, e.g. ``{"qp": 5, "tune": "film"}``.
|
|
157
|
+
See :ref:`extra_options` for details.
|
|
158
|
+
|
|
159
|
+
Returns:
|
|
160
|
+
A video stream object. Use its :meth:`~VideoStream.add_frames`
|
|
161
|
+
method to feed frames into the stream.
|
|
162
|
+
"""
|
|
163
|
+
if device is None:
|
|
164
|
+
device = torch.get_default_device()
|
|
165
|
+
device = str(device)
|
|
166
|
+
preset = str(preset) if isinstance(preset, int) else preset
|
|
167
|
+
stream_identifier = _core.streaming_encoder_add_video_stream(
|
|
168
|
+
self._encoder_tensor,
|
|
169
|
+
height=height,
|
|
170
|
+
width=width,
|
|
171
|
+
frame_rate=frame_rate,
|
|
172
|
+
device=device,
|
|
173
|
+
codec=codec,
|
|
174
|
+
pixel_format=pixel_format,
|
|
175
|
+
crf=crf,
|
|
176
|
+
preset=preset,
|
|
177
|
+
extra_options=[
|
|
178
|
+
str(x) for k, v in (extra_options or {}).items() for x in (k, v)
|
|
179
|
+
],
|
|
180
|
+
)
|
|
181
|
+
return VideoStream(self._encoder_tensor, stream_identifier)
|
|
182
|
+
|
|
183
|
+
def add_audio(
|
|
184
|
+
self,
|
|
185
|
+
*,
|
|
186
|
+
sample_rate: int,
|
|
187
|
+
num_channels: int,
|
|
188
|
+
bit_rate: int | None = None,
|
|
189
|
+
out_num_channels: int | None = None,
|
|
190
|
+
out_sample_rate: int | None = None,
|
|
191
|
+
) -> AudioStream:
|
|
192
|
+
"""Add an audio stream to the encoder.
|
|
193
|
+
|
|
194
|
+
Must be called before :meth:`open_file` or :meth:`open_file_like`.
|
|
195
|
+
|
|
196
|
+
Args:
|
|
197
|
+
sample_rate (int): The sample rate of the **input** samples.
|
|
198
|
+
num_channels (int): The number of channels of the **input** samples.
|
|
199
|
+
bit_rate (int, optional): The output bit rate. Encoders typically
|
|
200
|
+
support a finite set of bit rate values, so ``bit_rate`` will be
|
|
201
|
+
matched to one of those supported values. The default is chosen
|
|
202
|
+
by FFmpeg.
|
|
203
|
+
out_num_channels (int, optional): The number of channels of the
|
|
204
|
+
encoded output. By default, the input ``num_channels`` is used.
|
|
205
|
+
out_sample_rate (int, optional): The sample rate of the encoded
|
|
206
|
+
output. By default, the input ``sample_rate`` is used.
|
|
207
|
+
|
|
208
|
+
Returns:
|
|
209
|
+
An audio stream object. Use its :meth:`~AudioStream.add_samples`
|
|
210
|
+
method to feed samples into the stream.
|
|
211
|
+
"""
|
|
212
|
+
stream_identifier = _core.streaming_encoder_add_audio_stream(
|
|
213
|
+
self._encoder_tensor,
|
|
214
|
+
sample_rate=sample_rate,
|
|
215
|
+
num_channels=num_channels,
|
|
216
|
+
bit_rate=bit_rate,
|
|
217
|
+
output_num_channels=out_num_channels,
|
|
218
|
+
output_sample_rate=out_sample_rate,
|
|
219
|
+
)
|
|
220
|
+
return AudioStream(self._encoder_tensor, stream_identifier)
|
|
221
|
+
|
|
222
|
+
def open_file(self, dest: str | Path) -> "Encoder":
|
|
223
|
+
"""Open a file for writing the encoded output.
|
|
224
|
+
|
|
225
|
+
Must be called after all streams have been added via :meth:`add_video`
|
|
226
|
+
and/or :meth:`add_audio`. The file extension determines the container
|
|
227
|
+
format (e.g. ``.mp4``, ``.mkv``).
|
|
228
|
+
|
|
229
|
+
Args:
|
|
230
|
+
dest (str or ``pathlib.Path``): The path to the output file.
|
|
231
|
+
|
|
232
|
+
Returns:
|
|
233
|
+
Encoder: Returns ``self`` for method chaining.
|
|
234
|
+
"""
|
|
235
|
+
_core.streaming_encoder_open_file(self._encoder_tensor, str(dest))
|
|
236
|
+
return self
|
|
237
|
+
|
|
238
|
+
def open_file_like(self, dest, *, format: str) -> "Encoder":
|
|
239
|
+
"""Open a file-like object for writing the encoded output.
|
|
240
|
+
|
|
241
|
+
Must be called after all streams have been added via :meth:`add_video`
|
|
242
|
+
and/or :meth:`add_audio`.
|
|
243
|
+
|
|
244
|
+
Args:
|
|
245
|
+
dest: A file-like object that supports ``write()`` and ``seek()``
|
|
246
|
+
methods, such as ``io.BytesIO()``, an open file in binary write
|
|
247
|
+
mode, etc. Methods must have the following signature:
|
|
248
|
+
``write(data: bytes) -> int`` and ``seek(offset: int, whence:
|
|
249
|
+
int = 0) -> int``.
|
|
250
|
+
format (str): The container format of the encoded output, e.g.
|
|
251
|
+
``"mp4"``, ``"mov"``, ``"mkv"``, ``"avi"``, ``"webm"``, etc.
|
|
252
|
+
|
|
253
|
+
Returns:
|
|
254
|
+
Encoder: Returns ``self`` for method chaining.
|
|
255
|
+
"""
|
|
256
|
+
_core.streaming_encoder_open_file_like(self._encoder_tensor, format, dest)
|
|
257
|
+
return self
|
|
258
|
+
|
|
259
|
+
def close(self) -> None:
|
|
260
|
+
"""Flush all remaining data and close the encoder.
|
|
261
|
+
|
|
262
|
+
This must be called when encoding is complete to ensure all buffered
|
|
263
|
+
data is written. Using the encoder as a context manager (``with``
|
|
264
|
+
statement) calls this automatically.
|
|
265
|
+
"""
|
|
266
|
+
_core.streaming_encoder_close(self._encoder_tensor)
|
|
267
|
+
|
|
268
|
+
def __enter__(self) -> "Encoder":
|
|
269
|
+
return self
|
|
270
|
+
|
|
271
|
+
def __exit__(self, exc_type, exc_val, exc_tb) -> None:
|
|
272
|
+
self.close()
|
|
@@ -0,0 +1,227 @@
|
|
|
1
|
+
import io
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
from typing import Any
|
|
4
|
+
|
|
5
|
+
import torch
|
|
6
|
+
from torch import Tensor
|
|
7
|
+
|
|
8
|
+
from torchcodec._internally_replaced_utils import load_core_libraries
|
|
9
|
+
from torchcodec.encoders._multi_stream_encoder import Encoder
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class VideoEncoder:
|
|
13
|
+
"""A single-stream video encoder on CPU or CUDA.
|
|
14
|
+
|
|
15
|
+
.. note::
|
|
16
|
+
This is a convenience class for simple, one-shot video encoding. For
|
|
17
|
+
multi-stream encoding (e.g. video + audio), incremental encoding, or
|
|
18
|
+
mixing CPU and CUDA streams, use :class:`~torchcodec.encoders.Encoder`
|
|
19
|
+
instead. See
|
|
20
|
+
:ref:`sphx_glr_generated_examples_encoding_video_encoding.py` for a
|
|
21
|
+
tutorial.
|
|
22
|
+
|
|
23
|
+
Args:
|
|
24
|
+
frames (``torch.Tensor``): The frames to encode. This must be a 4D
|
|
25
|
+
tensor of shape ``(N, C, H, W)`` where N is the number of frames,
|
|
26
|
+
C is 3 channels (RGB), H is height, and W is width.
|
|
27
|
+
Values must be uint8 in the range ``[0, 255]``.
|
|
28
|
+
The tensor can be on CPU or CUDA. The device of the tensor
|
|
29
|
+
determines which encoder is used (CPU or GPU).
|
|
30
|
+
frame_rate (float): The frame rate of the **input** ``frames``. Also defines the encoded **output** frame rate.
|
|
31
|
+
"""
|
|
32
|
+
|
|
33
|
+
def __init__(self, frames: Tensor, *, frame_rate: float):
|
|
34
|
+
torch._C._log_api_usage_once("torchcodec.encoders.VideoEncoder")
|
|
35
|
+
load_core_libraries()
|
|
36
|
+
if not isinstance(frames, Tensor):
|
|
37
|
+
raise ValueError(f"Expected frames to be a Tensor, got {type(frames) = }.")
|
|
38
|
+
if frames.ndim != 4:
|
|
39
|
+
raise ValueError(f"Expected 4D frames, got {frames.shape = }.")
|
|
40
|
+
if frames.dtype != torch.uint8:
|
|
41
|
+
raise ValueError(f"Expected uint8 frames, got {frames.dtype = }.")
|
|
42
|
+
if frame_rate <= 0:
|
|
43
|
+
raise ValueError(f"{frame_rate = } must be > 0.")
|
|
44
|
+
|
|
45
|
+
self._frames = frames
|
|
46
|
+
self._frame_rate = frame_rate
|
|
47
|
+
|
|
48
|
+
def _get_add_video_kwargs(
|
|
49
|
+
self,
|
|
50
|
+
*,
|
|
51
|
+
codec: str | None = None,
|
|
52
|
+
pixel_format: str | None = None,
|
|
53
|
+
crf: int | float | None = None,
|
|
54
|
+
preset: str | int | None = None,
|
|
55
|
+
extra_options: dict[str, Any] | None = None,
|
|
56
|
+
) -> dict:
|
|
57
|
+
preset = str(preset) if isinstance(preset, int) else preset
|
|
58
|
+
return dict(
|
|
59
|
+
height=self._frames.shape[2],
|
|
60
|
+
width=self._frames.shape[3],
|
|
61
|
+
frame_rate=self._frame_rate,
|
|
62
|
+
device=str(self._frames.device),
|
|
63
|
+
codec=codec,
|
|
64
|
+
pixel_format=pixel_format,
|
|
65
|
+
crf=crf,
|
|
66
|
+
preset=preset,
|
|
67
|
+
extra_options=extra_options,
|
|
68
|
+
)
|
|
69
|
+
|
|
70
|
+
def to_file(
|
|
71
|
+
self,
|
|
72
|
+
dest: str | Path,
|
|
73
|
+
*,
|
|
74
|
+
codec: str | None = None,
|
|
75
|
+
pixel_format: str | None = None,
|
|
76
|
+
crf: int | float | None = None,
|
|
77
|
+
preset: str | int | None = None,
|
|
78
|
+
extra_options: dict[str, Any] | None = None,
|
|
79
|
+
) -> None:
|
|
80
|
+
"""Encode frames into a file.
|
|
81
|
+
|
|
82
|
+
Args:
|
|
83
|
+
dest (str or ``pathlib.Path``): The path to the output file, e.g.
|
|
84
|
+
``video.mp4``. The extension of the file determines the video
|
|
85
|
+
container format.
|
|
86
|
+
codec (str, optional): The codec to use for encoding (e.g., "libx264",
|
|
87
|
+
"h264"). If not specified, the default codec
|
|
88
|
+
for the container format will be used.
|
|
89
|
+
See :ref:`codec_selection` for details.
|
|
90
|
+
pixel_format (str, optional): The pixel format for encoding (e.g.,
|
|
91
|
+
"yuv420p", "yuv444p"). If not specified, uses codec's default format.
|
|
92
|
+
Must be left as ``None`` when encoding CUDA tensors.
|
|
93
|
+
See :ref:`pixel_format` for details.
|
|
94
|
+
crf (int or float, optional): Constant Rate Factor for encoding quality. Lower values
|
|
95
|
+
mean better quality. Valid range depends on the encoder (e.g. 0-51 for libx264).
|
|
96
|
+
Defaults to None (which will use encoder's default).
|
|
97
|
+
See :ref:`crf` for details.
|
|
98
|
+
preset (str or int, optional): Encoder option that controls the tradeoff between
|
|
99
|
+
encoding encoding speed and compression (output size). Valid on the encoder (commonly
|
|
100
|
+
a string: "fast", "medium", "slow"). Defaults to None
|
|
101
|
+
(which will use encoder's default).
|
|
102
|
+
See :ref:`preset` for details.
|
|
103
|
+
extra_options (dict[str, Any], optional): A dictionary of additional
|
|
104
|
+
encoder options to pass, e.g. ``{"qp": 5, "tune": "film"}``.
|
|
105
|
+
See :ref:`extra_options` for details.
|
|
106
|
+
"""
|
|
107
|
+
encoder = Encoder()
|
|
108
|
+
video = encoder.add_video(
|
|
109
|
+
**self._get_add_video_kwargs(
|
|
110
|
+
codec=codec,
|
|
111
|
+
pixel_format=pixel_format,
|
|
112
|
+
crf=crf,
|
|
113
|
+
preset=preset,
|
|
114
|
+
extra_options=extra_options,
|
|
115
|
+
)
|
|
116
|
+
)
|
|
117
|
+
with encoder.open_file(dest):
|
|
118
|
+
video.add_frames(self._frames)
|
|
119
|
+
|
|
120
|
+
def to_tensor(
|
|
121
|
+
self,
|
|
122
|
+
format: str,
|
|
123
|
+
*,
|
|
124
|
+
codec: str | None = None,
|
|
125
|
+
pixel_format: str | None = None,
|
|
126
|
+
crf: int | float | None = None,
|
|
127
|
+
preset: str | int | None = None,
|
|
128
|
+
extra_options: dict[str, Any] | None = None,
|
|
129
|
+
) -> Tensor:
|
|
130
|
+
"""Encode frames into raw bytes, as a 1D uint8 Tensor.
|
|
131
|
+
|
|
132
|
+
Args:
|
|
133
|
+
format (str): The container format of the encoded frames, e.g. "mp4", "mov",
|
|
134
|
+
"mkv", "avi", "webm", "flv", etc.
|
|
135
|
+
codec (str, optional): The codec to use for encoding (e.g., "libx264",
|
|
136
|
+
"h264"). If not specified, the default codec
|
|
137
|
+
for the container format will be used.
|
|
138
|
+
See :ref:`codec_selection` for details.
|
|
139
|
+
pixel_format (str, optional): The pixel format to encode frames into (e.g.,
|
|
140
|
+
"yuv420p", "yuv444p"). If not specified, uses codec's default format.
|
|
141
|
+
Must be left as ``None`` when encoding CUDA tensors.
|
|
142
|
+
See :ref:`pixel_format` for details.
|
|
143
|
+
crf (int or float, optional): Constant Rate Factor for encoding quality. Lower values
|
|
144
|
+
mean better quality. Valid range depends on the encoder (e.g. 0-51 for libx264).
|
|
145
|
+
Defaults to None (which will use encoder's default).
|
|
146
|
+
See :ref:`crf` for details.
|
|
147
|
+
preset (str or int, optional): Encoder option that controls the tradeoff between
|
|
148
|
+
encoding encoding speed and compression (output size). Valid on the encoder (commonly
|
|
149
|
+
a string: "fast", "medium", "slow"). Defaults to None
|
|
150
|
+
(which will use encoder's default).
|
|
151
|
+
See :ref:`preset` for details.
|
|
152
|
+
extra_options (dict[str, Any], optional): A dictionary of additional
|
|
153
|
+
encoder options to pass, e.g. ``{"qp": 5, "tune": "film"}``.
|
|
154
|
+
See :ref:`extra_options` for details.
|
|
155
|
+
|
|
156
|
+
Returns:
|
|
157
|
+
Tensor: The raw encoded bytes as 1D uint8 Tensor on CPU regardless of the device of the input frames.
|
|
158
|
+
"""
|
|
159
|
+
buf = io.BytesIO()
|
|
160
|
+
encoder = Encoder()
|
|
161
|
+
video = encoder.add_video(
|
|
162
|
+
**self._get_add_video_kwargs(
|
|
163
|
+
codec=codec,
|
|
164
|
+
pixel_format=pixel_format,
|
|
165
|
+
crf=crf,
|
|
166
|
+
preset=preset,
|
|
167
|
+
extra_options=extra_options,
|
|
168
|
+
)
|
|
169
|
+
)
|
|
170
|
+
with encoder.open_file_like(buf, format=format):
|
|
171
|
+
video.add_frames(self._frames)
|
|
172
|
+
return torch.frombuffer(buf.getbuffer(), dtype=torch.uint8)
|
|
173
|
+
|
|
174
|
+
def to_file_like(
|
|
175
|
+
self,
|
|
176
|
+
file_like,
|
|
177
|
+
format: str,
|
|
178
|
+
*,
|
|
179
|
+
codec: str | None = None,
|
|
180
|
+
pixel_format: str | None = None,
|
|
181
|
+
crf: int | float | None = None,
|
|
182
|
+
preset: str | int | None = None,
|
|
183
|
+
extra_options: dict[str, Any] | None = None,
|
|
184
|
+
) -> None:
|
|
185
|
+
"""Encode frames into a file-like object.
|
|
186
|
+
|
|
187
|
+
Args:
|
|
188
|
+
file_like: A file-like object that supports ``write()`` and
|
|
189
|
+
``seek()`` methods, such as io.BytesIO(), an open file in binary
|
|
190
|
+
write mode, etc. Methods must have the following signature:
|
|
191
|
+
``write(data: bytes) -> int`` and ``seek(offset: int, whence:
|
|
192
|
+
int = 0) -> int``.
|
|
193
|
+
format (str): The container format of the encoded frames, e.g. "mp4", "mov",
|
|
194
|
+
"mkv", "avi", "webm", "flv", etc.
|
|
195
|
+
codec (str, optional): The codec to use for encoding (e.g., "libx264",
|
|
196
|
+
"h264"). If not specified, the default codec
|
|
197
|
+
for the container format will be used.
|
|
198
|
+
See :ref:`codec_selection` for details.
|
|
199
|
+
pixel_format (str, optional): The pixel format for encoding (e.g.,
|
|
200
|
+
"yuv420p", "yuv444p"). If not specified, uses codec's default format.
|
|
201
|
+
Must be left as ``None`` when encoding CUDA tensors.
|
|
202
|
+
See :ref:`pixel_format` for details.
|
|
203
|
+
crf (int or float, optional): Constant Rate Factor for encoding quality. Lower values
|
|
204
|
+
mean better quality. Valid range depends on the encoder (e.g. 0-51 for libx264).
|
|
205
|
+
Defaults to None (which will use encoder's default).
|
|
206
|
+
See :ref:`crf` for details.
|
|
207
|
+
preset (str or int, optional): Encoder option that controls the tradeoff between
|
|
208
|
+
encoding encoding speed and compression (output size). Valid on the encoder (commonly
|
|
209
|
+
a string: "fast", "medium", "slow"). Defaults to None
|
|
210
|
+
(which will use encoder's default).
|
|
211
|
+
See :ref:`preset` for details.
|
|
212
|
+
extra_options (dict[str, Any], optional): A dictionary of additional
|
|
213
|
+
encoder options to pass, e.g. ``{"qp": 5, "tune": "film"}``.
|
|
214
|
+
See :ref:`extra_options` for details.
|
|
215
|
+
"""
|
|
216
|
+
encoder = Encoder()
|
|
217
|
+
video = encoder.add_video(
|
|
218
|
+
**self._get_add_video_kwargs(
|
|
219
|
+
codec=codec,
|
|
220
|
+
pixel_format=pixel_format,
|
|
221
|
+
crf=crf,
|
|
222
|
+
preset=preset,
|
|
223
|
+
extra_options=extra_options,
|
|
224
|
+
)
|
|
225
|
+
)
|
|
226
|
+
with encoder.open_file_like(file_like, format=format):
|
|
227
|
+
video.add_frames(self._frames)
|
torchcodec/jpeg8.dll
ADDED
|
Binary file
|
torchcodec/libavif.dll
ADDED
|
Binary file
|
torchcodec/libpng16.dll
ADDED
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
torchcodec/libwebp.dll
ADDED
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
torchcodec/libzstd.dll
ADDED
|
Binary file
|
torchcodec/py.typed
ADDED
|
File without changes
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
from collections.abc import Callable
|
|
2
|
+
from typing import TypeVar
|
|
3
|
+
|
|
4
|
+
from torchcodec import FrameBatch
|
|
5
|
+
|
|
6
|
+
_INT_OR_FLOAT = TypeVar("_INT_OR_FLOAT", int, float)
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def _repeat_last_policy(
|
|
10
|
+
values: list[_INT_OR_FLOAT], desired_len: int
|
|
11
|
+
) -> list[_INT_OR_FLOAT]:
|
|
12
|
+
# values = [1, 2, 3], desired_len = 5
|
|
13
|
+
# output = [1, 2, 3, 3, 3]
|
|
14
|
+
values += [values[-1]] * (desired_len - len(values))
|
|
15
|
+
return values
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _wrap_policy(values: list[_INT_OR_FLOAT], desired_len: int) -> list[_INT_OR_FLOAT]:
|
|
19
|
+
# values = [1, 2, 3], desired_len = 5
|
|
20
|
+
# output = [1, 2, 3, 1, 2]
|
|
21
|
+
return (values * (desired_len // len(values) + 1))[:desired_len]
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _error_policy(
|
|
25
|
+
frames_indices: list[_INT_OR_FLOAT], desired_len: int
|
|
26
|
+
) -> list[_INT_OR_FLOAT]:
|
|
27
|
+
raise ValueError(
|
|
28
|
+
"You set the 'error' policy, and the sampler tried to decode a frame "
|
|
29
|
+
"that is beyond the number of frames in the video. "
|
|
30
|
+
"Try to leave sampling_range_end to its default value?"
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
_POLICY_FUNCTION_TYPE = Callable[[list[_INT_OR_FLOAT], int], list[_INT_OR_FLOAT]]
|
|
35
|
+
|
|
36
|
+
_POLICY_FUNCTIONS: dict[str, _POLICY_FUNCTION_TYPE] = {
|
|
37
|
+
"repeat_last": _repeat_last_policy,
|
|
38
|
+
"wrap": _wrap_policy,
|
|
39
|
+
"error": _error_policy,
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _validate_common_params(*, decoder, num_frames_per_clip, policy):
|
|
44
|
+
if len(decoder) < 1:
|
|
45
|
+
raise ValueError(
|
|
46
|
+
f"Decoder must have at least one frame, found {len(decoder)} frames."
|
|
47
|
+
)
|
|
48
|
+
|
|
49
|
+
if num_frames_per_clip <= 0:
|
|
50
|
+
raise ValueError(
|
|
51
|
+
f"num_frames_per_clip ({num_frames_per_clip}) must be strictly positive"
|
|
52
|
+
)
|
|
53
|
+
if policy not in _POLICY_FUNCTIONS.keys():
|
|
54
|
+
raise ValueError(
|
|
55
|
+
f"Invalid policy ({policy}). Supported values are {_POLICY_FUNCTIONS.keys()}."
|
|
56
|
+
)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _reshape_4d_framebatch_into_5d(
|
|
60
|
+
*,
|
|
61
|
+
frames: FrameBatch,
|
|
62
|
+
num_clips: int,
|
|
63
|
+
num_frames_per_clip: int,
|
|
64
|
+
) -> FrameBatch:
|
|
65
|
+
last_3_dims = frames.data.shape[-3:]
|
|
66
|
+
return FrameBatch(
|
|
67
|
+
data=frames.data.view(num_clips, num_frames_per_clip, *last_3_dims),
|
|
68
|
+
pts_seconds=frames.pts_seconds.view(num_clips, num_frames_per_clip),
|
|
69
|
+
duration_seconds=frames.duration_seconds.view(num_clips, num_frames_per_clip),
|
|
70
|
+
)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
_FRAMEBATCH_RETURN_DOCS = """
|
|
74
|
+
Returns:
|
|
75
|
+
FrameBatch:
|
|
76
|
+
The sampled :term:`clips`, as a 5D :class:`~torchcodec.FrameBatch`.
|
|
77
|
+
The shape of the ``data`` field is (``num_clips``,
|
|
78
|
+
``num_frames_per_clips``, ...) where ... is (H, W, C) or (C, H, W)
|
|
79
|
+
depending on the ``dimension_order`` parameter of
|
|
80
|
+
:class:`~torchcodec.decoders.VideoDecoder`. The shape of the
|
|
81
|
+
``pts_seconds`` and ``duration_seconds`` fields is (``num_clips``,
|
|
82
|
+
``num_frames_per_clips``).
|
|
83
|
+
"""
|