text
stringlengths
0
2.2M
* LICENSE file in the root directory of this source tree.
*/
#include "flashlight/pkg/speech/augmentation/SoxWrapper.h"
#include <algorithm>
#include <fstream>
#include <memory>
#include <mutex>
#include <sstream>
#include <glog/logging.h>
#include <sox.h>
#include "flashlight/pkg/speech/data/Sound.h"
#include "flashlight/fl/common/Logging.h"
namespace fl {
namespace pkg {
namespace speech {
namespace sfx {
namespace {
struct SoxData {
std::vector<float>* data;
size_t index = 0;
};
static int outputFlow(
sox_effect_t* effp LSX_UNUSED,
sox_sample_t const* ibuf,
sox_sample_t* obuf LSX_UNUSED,
size_t* isamp,
size_t* osamp) {
if (*isamp) {
auto priv = static_cast<SoxData*>(effp->priv);
int i = 0;
for (; i < *isamp; ++i) {
SOX_SAMPLE_LOCALS;
priv->data->push_back(SOX_SAMPLE_TO_FLOAT_32BIT(ibuf[i], effp->clips));
}
if (i != *isamp) {
LOG(ERROR) << "outputFlow number of bytes written=" << i
<< " expected=" << *isamp
<< " priv->data->size()=" << priv->data->size();
return SOX_EOF;
}
}
*osamp = 0;
return SOX_SUCCESS;
}
int inputDrain(sox_effect_t* effp, sox_sample_t* obuf, size_t* osamp) {
auto priv = static_cast<SoxData*>(effp->priv);
int i = 0;
for (; i < *osamp && priv->index < priv->data->size(); ++i, ++priv->index) {
SOX_SAMPLE_LOCALS;
obuf[i] =
SOX_FLOAT_32BIT_TO_SAMPLE(priv->data->at(priv->index), effp->clips);
}
*osamp = i;
return *osamp ? SOX_SUCCESS : SOX_EOF;
}
std::unique_ptr<sox_signalinfo_t> createSignalInfo(size_t sampleRate) {
auto sigInfo = std::make_unique<sox_signalinfo_t>();
*sigInfo = {
.rate = (sox_rate_t)sampleRate,
.channels = 1, // Sounds effects are limited to single channel
.precision = 16, // Any valid value is ok here.
.length = 0,
.mult = nullptr};
return sigInfo;
}
} // namespace
std::unique_ptr<SoxWrapper> SoxWrapper::instance_;
SoxWrapper::SoxWrapper(size_t sampleRate)
: signalInfo_(createSignalInfo(sampleRate)) {
FL_SOX_CHECK(sox_init());
}
SoxWrapper::~SoxWrapper() {
sox_quit();
}
SoxWrapper* SoxWrapper::instance(size_t sampleRate /* =16000*/) {
if (!instance_) {
auto s = new SoxWrapper(sampleRate);
instance_.reset(s);
}
return instance_.get();
}