1010#include < string>
1111
1212#include " src/torchcodec/_core/AVIOFileLikeContext.h"
13+ #include " src/torchcodec/_core/Encoder.h"
1314#include " src/torchcodec/_core/SingleStreamDecoder.h"
15+ #include " src/torchcodec/_core/StreamOptions.h"
1416
1517namespace py = pybind11;
1618
@@ -31,19 +33,55 @@ int64_t create_from_file_like(
3133 realSeek = seekModeFromString (seek_mode.value ());
3234 }
3335
34- auto avioContextHolder = std::make_unique<AVIOFileLikeContext>(file_like);
36+ auto avioContextHolder =
37+ std::make_unique<AVIOFileLikeContext>(file_like, /* isForWriting=*/ false );
3538
3639 SingleStreamDecoder* decoder =
3740 new SingleStreamDecoder (std::move (avioContextHolder), realSeek);
3841 return reinterpret_cast <int64_t >(decoder);
3942}
4043
44+ void encode_audio_to_file_like (
45+ int64_t data_ptr,
46+ const std::vector<int64_t >& shape,
47+ int64_t sample_rate,
48+ std::string_view format,
49+ py::object file_like,
50+ std::optional<int64_t > bit_rate = std::nullopt ,
51+ std::optional<int64_t > num_channels = std::nullopt ,
52+ std::optional<int64_t > desired_sample_rate = std::nullopt ) {
53+ // We assume float32 *and* contiguity, this must be enforced by the caller.
54+ auto tensor_options = torch::TensorOptions ().dtype (torch::kFloat32 );
55+ auto samples = torch::from_blob (
56+ reinterpret_cast <void *>(data_ptr), shape, tensor_options);
57+
58+ // TODO Fix implicit int conversion:
59+ // https://github.com/pytorch/torchcodec/issues/679
60+ // same for sample_rate parameter below
61+ AudioStreamOptions audioStreamOptions;
62+ audioStreamOptions.bitRate = bit_rate;
63+ audioStreamOptions.numChannels = num_channels;
64+ audioStreamOptions.sampleRate = desired_sample_rate;
65+
66+ auto avioContextHolder =
67+ std::make_unique<AVIOFileLikeContext>(file_like, /* isForWriting=*/ true );
68+
69+ AudioEncoder encoder (
70+ samples,
71+ static_cast <int >(sample_rate),
72+ format,
73+ std::move (avioContextHolder),
74+ audioStreamOptions);
75+ encoder.encode ();
76+ }
77+
4178#ifndef PYBIND_OPS_MODULE_NAME
4279#error PYBIND_OPS_MODULE_NAME must be defined!
4380#endif
4481
4582PYBIND11_MODULE (PYBIND_OPS_MODULE_NAME, m) {
4683 m.def (" create_from_file_like" , &create_from_file_like);
84+ m.def (" encode_audio_to_file_like" , &encode_audio_to_file_like);
4785}
4886
4987} // namespace facebook::torchcodec
0 commit comments