10
10
#include < string>
11
11
12
12
#include " src/torchcodec/_core/AVIOFileLikeContext.h"
13
+ #include " src/torchcodec/_core/Encoder.h"
13
14
#include " src/torchcodec/_core/SingleStreamDecoder.h"
15
+ #include " src/torchcodec/_core/StreamOptions.h"
14
16
15
17
namespace py = pybind11;
16
18
@@ -31,19 +33,55 @@ int64_t create_from_file_like(
31
33
realSeek = seekModeFromString (seek_mode.value ());
32
34
}
33
35
34
- auto avioContextHolder = std::make_unique<AVIOFileLikeContext>(file_like);
36
+ auto avioContextHolder =
37
+ std::make_unique<AVIOFileLikeContext>(file_like, /* isForWriting=*/ false );
35
38
36
39
SingleStreamDecoder* decoder =
37
40
new SingleStreamDecoder (std::move (avioContextHolder), realSeek);
38
41
return reinterpret_cast <int64_t >(decoder);
39
42
}
40
43
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
+
41
78
#ifndef PYBIND_OPS_MODULE_NAME
42
79
#error PYBIND_OPS_MODULE_NAME must be defined!
43
80
#endif
44
81
45
82
PYBIND11_MODULE (PYBIND_OPS_MODULE_NAME, m) {
46
83
m.def (" create_from_file_like" , &create_from_file_like);
84
+ m.def (" encode_audio_to_file_like" , &encode_audio_to_file_like);
47
85
}
48
86
49
87
} // namespace facebook::torchcodec
0 commit comments